Home  >  Article  >  Backend Development  >  How to Create Graphs with Logarithmic Axes in Matplotlib?

How to Create Graphs with Logarithmic Axes in Matplotlib?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 02:51:02175browse

How to Create Graphs with Logarithmic Axes in Matplotlib?

How to Plot Graphs with Logarithmic Axes in Matplotlib

In data visualization with Matplotlib, logarithmic scales are useful when data values span several orders of magnitude. To create graphs with logarithmic axes, you can use the Axes.set_yscale method.

Problem:

You want to plot a graph with one logarithmic axis using Matplotlib.

<code class="python">import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]  # exponential
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)
plt.show()</code>

Solution:

Add the following line to your code:

<code class="python">ax.set_yscale('log')</code>

You can use 'linear' to switch back to a linear scale.

Here's the modified code:

<code class="python">import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)

ax.set_yscale('log')

plt.show()</code>

Result:

The resulting graph will have one axis plotted on a logarithmic scale, displaying the data values as logarithmic ticks. This allows for a more compact visualization of data that spans multiple orders of magnitude.

The above is the detailed content of How to Create Graphs with Logarithmic Axes in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn