Python - Matplotlib绘图库使用详解2(网格、坐标轴、标题、双轴图)
作者:hangge | 2022-08-05 08:10
三、网格、坐标轴、标题、双轴图
1,网格格式
(1)使用 grid() 方法可以开启或者关闭画布中的网格:
import matplotlib.pyplot as plt #开启网格 plt.grid() #准备数据 langs = ['C', 'C++', 'Java', 'Python', 'PHP'] students = [23,17,35,29,12] #绘制柱状图 plt.bar(langs,students) plt.show()
(2)grid() 函数还可以设置网格的颜色(color)、线型(ls)以及线宽(lw)等属性:
import matplotlib.pyplot as plt #开启网格 plt.grid(color='r', ls = '-.', lw = 0.75) #准备数据 langs = ['C', 'C++', 'Java', 'Python', 'PHP'] students = [23,17,35,29,12] #绘制柱状图 plt.bar(langs,students) plt.show()
2,坐标轴格式
我们可以通过指定轴的颜色和宽度,从而对进行显示格式设置。如果将轴的颜色设置为 None,那么它便成为隐藏状态:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
#为左侧轴,底部轴添加颜色
ax.spines['bottom'].set_color('red')
ax.spines['left'].set_color('blue')
ax.spines['left'].set_linewidth(2)
#将右侧轴、顶部轴设置为None
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
#准备数据
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
#绘制柱状图
plt.bar(langs,students)
plt.show()
3,坐标轴范围
Matplotlib 可以根据自变量与因变量的取值范围,自动设置 x 轴与 y 轴的数值大小。我们也可以用自定义的方式,通过 set_xlim() 和 set_ylim() 对 x、y 轴的数值范围进行设置。
import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_axes([0,0,1,1]) #设置y轴 ax.set_ylim(0,100) #设置x轴 ax.set_xlim(0,10) #准备数据 x = [1,2,3,4,5] y = [23,17,35,29,12] #绘制柱状图 plt.bar(x,y) plt.show()
4,标题文字
(1)我们可以通过 title() 方法设置整个图表的标题:
import matplotlib.pyplot as plt
#设置标题
plt.title("My Chart")
#准备数据
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
#绘制柱状图
plt.bar(langs,students)
plt.show()
(2)还可以通过 xlabel() 和 ylabel() 方法来分别设置 x 轴、y 轴的标签:
import matplotlib.pyplot as plt
#设置标题
plt.title("My Chart")
#设置x轴标签
plt.xlabel("x axis")
#设置y轴标签
plt.ylabel("y axis")
#准备数据
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
#绘制柱状图
plt.bar(langs,students)
plt.show()
5,双轴图
在一些应用场景中,有时需要绘制两个 x 轴或两个 y 轴,这样可以更直观地显现图像,从而获取更有效的数据。Matplotlib 提供的 twinx() 和 twiny() 函数可以实现绘制双轴的功能。
import matplotlib.pyplot as plt
#创建图形对象
fig = plt.figure()
#添加子图区域
ax1 = fig.add_axes([0,0,1,1])
#准备数据
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
temperature = [36.5, 37.3, 37.9, 39.2, 39.5, 40.8, 41.1]
humidity = [80.4, 80.2, 80.1, 79.9, 80.0, 80.1, 80.2]
#绘制温度曲线
ax1.plot(days, temperature, color='red', label='Temperature')
#添加双轴
ax2 = ax1.twinx()
#绘制相对湿度曲线
ax2.plot(days, humidity, color='blue', label='Humidity')
#设置y轴标签
ax1.set_ylabel('Temperature')
ax2.set_ylabel('Humidity')
#绘制图例
fig.legend(labels = ('Temperature','Humidity'),loc='upper right')
plt.show()
全部评论(0)