📅  最后修改于: 2023-12-03 14:47:44.761000             🧑  作者: Mango
In data visualization, subplots are a useful way to display multiple plots within a single figure. One common requirement is to show y-tick labels as percentages. This can be achieved using the matplotlib.pyplot.subplots
function and customizing the y-tick labels.
In this tutorial, we will learn how to create subplots with y-axis tick labels formatted as percentages using Python and Matplotlib.
To follow along with this tutorial, you need to have the following installed:
You can install the required libraries using pip:
pip install matplotlib
First, we need to import the required libraries: numpy
and matplotlib.pyplot
.
import numpy as np
import matplotlib.pyplot as plt
Let's generate some sample data for our subplots. We will create two arrays, x
and y
, and plot them in separate subplots.
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
Next, we will create the subplots using the subplots()
function. To specify the number and arrangement of subplots, we pass the arguments num_rows
and num_cols
.
fig, axes = plt.subplots(nrows=2, ncols=1)
Now, we can plot the data in each subplot using the plot()
function.
axes[0].plot(x, y1)
axes[1].plot(x, y2)
To format the y-axis tick labels as percentages, we need to create a custom function and apply it to each subplot's y-axis.
def format_percent(value, tick_number):
return f'{value*100:.0f}%'
for ax in axes:
ax.yaxis.set_major_formatter(plt.FuncFormatter(format_percent))
Finally, we can add labels and titles to our subplots for better readability.
axes[0].set_ylabel('Amplitude')
axes[1].set_xlabel('Time')
axes[1].set_ylabel('Amplitude')
axes[0].set_title('Sine Wave')
axes[1].set_title('Cosine Wave')
To display the plot, we use the show()
function.
plt.show()
In this tutorial, we have learned how to create subplots with y-axis tick labels formatted as percentages using Python and Matplotlib. By customizing the y-tick labels using a custom function, we can easily display the desired formatting in our subplots.
Feel free to further customize your subplots by adding legends, grid lines, or other plot elements as per your requirements.