在python中使用mpl_toolkits.axes_grid1库的host_subplot()函数绘制双y轴水平条形图
发布时间:2023-12-29 18:01:31
在Python中,使用mpl_toolkits.axes_grid1库中的host_subplot()函数可以绘制双y轴水平条形图。下面是一个使用例子,详细介绍了如何使用这个函数来生成水平条形图。
首先,需要导入相应的库和模块:
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import host_subplot
接下来,我们需要创建一个数据列表,其中包含要绘制的两个水平条形图的数据。假设我们要比较两个产品在不同城市的销售数量:
cities = ['City A', 'City B', 'City C', 'City D'] product1_sales = [50, 60, 45, 55] # 产品1的销售数量 product2_sales = [40, 55, 50, 65] # 产品2的销售数量
然后,我们可以使用host_subplot()函数创建一个包含两个y轴的水平条形图。host_subplot()函数接受三个参数: 个参数是整个图表的尺寸,第二个参数是整个图表的布局,第三个参数是当前绘图的坐标轴。
fig, ax1 = plt.subplots(figsize=(8, 6)) ax2 = ax1.twinx() # 创建第二个y轴
接下来,我们可以使用bar()函数绘制水平条形图:
ax1.barh(cities, product1_sales, color='cyan') ax2.barh(cities, product2_sales, color='orange')
在此例子中,我们使用了两个不同的颜色来区分两个产品的销售数量。
然后,我们可以设置两个y轴的标签和标题:
ax1.set_ylabel('Cities')
ax1.set_xlabel('Product 1 Sales')
ax2.set_xlabel('Product 2 Sales')
plt.title('Comparison of Product Sales in Different Cities')
最后,我们可以使用legend()函数添加图例,并使用show()函数显示图表:
ax1.legend(['Product 1'], loc='upper right') ax2.legend(['Product 2'], loc='upper left') plt.show()
这个例子演示了如何使用mpl_toolkits.axes_grid1库的host_subplot()函数绘制双y轴水平条形图。你可以根据自己的需求进行调整和修改,以便生成你想要的图表。
