Matplotlib双轴图表添加数据标题及修复X轴整数显示问题
解决方案
针对你的两个需求,以下是具体的修改方案:
1. 为两个数据系列添加对应轴标题
直接给两个坐标轴设置ylabel,分别对应"open"和"closed":
- 给柱状图所在的
ax_1添加Y轴标题:ax_1.set_ylabel('open') - 给折线图所在的
ax_2添加Y轴标题:ax_2.set_ylabel('closed')
2. 修复X轴显示小数的问题
通过强制指定X轴刻度为数据中的整数年份,解决自动生成小数刻度的问题:
- 添加
ax_1.set_xticks(df['year']),让X轴仅显示数据里的整数年份 - 可选补充:添加
plt.xticks(rotation=45),旋转刻度标签避免因年份过多导致重叠
修改后的完整代码
import pandas as pd import matplotlib.pyplot as plt from matplotlib.cm import get_cmap data = {'year': [2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023], 'open': [70, 20, 24, 150, 80, 90, 60, 90, 20, 20, 20, 24, 150, 80, 90, 60, 90, 20, 30], 'closed':[30, 14, 20, 10, 20, 40, 10, 10, 10, 10, 30, 14, 20, 10, 20, 40, 10, 10, 10]} df = pd.DataFrame(data, columns = ['year', 'open', 'closed']) fig, ax_1 = plt.subplots(figsize = (8, 5)) ax_2 = ax_1.twinx() cmap = get_cmap('tab10') ax_1.bar(df['year'], df['open'], label = 'open', color = cmap(0)) ax_2.plot(df['year'], df['closed'], label = 'closed', color = cmap(0.1),linewidth = '4.5') # 添加轴标题 ax_1.set_ylabel('open') ax_2.set_ylabel('closed') handles_1, labels_1 = ax_1.get_legend_handles_labels() handles_2, labels_2 = ax_2.get_legend_handles_labels() ax_1.set_ylim(0, 160) ax_2.set_ylim(0, 45) ax_1.legend(handles = handles_1 + handles_2, labels = labels_1 + labels_2, loc = 'upper left', shadow = True) ax_1.grid(axis = 'y') ax_1.set_title('Sales comparison') # 修复X轴刻度问题,可选添加旋转避免重叠 ax_1.set_xticks(df['year']) plt.xticks(rotation=45) plt.show()
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

