首页 > 解决方案 > Matplotlib x 轴限制范围

问题描述

所以我一直在尝试绘制一些数据。x 轴限制为两年。我的问题很简单,当可用数据在 2015Q1 - 2020Q1 之间时,有人可以解释为什么 X 轴仅限于 2015Q1 - 2017Q1 的日期范围。我的代码有什么遗漏或不正确吗?

dd2

qtr     median  count
0   2015Q1  1290000.0   27
1   2015Q2  1330000.0   43
2   2015Q3  1570000.0   21
3   2015Q4  1371000.0   20
4   2016Q1  1386500.0   20
5   2016Q2  1767500.0   22
6   2016Q3  1427500.0   32
7   2016Q4  1501000.0   31
8   2017Q1  1700000.0   29
9   2017Q2  1630000.0   15
10  2017Q3  1687500.0   24
11  2017Q4  1450000.0   15
12  2018Q1  1505000.0   13
13  2018Q2  1494000.0   14
14  2018Q3  1415000.0   21
15  2018Q4  1150000.0   15
16  2019Q1  1228000.0   15
17  2019Q2  1352500.0   12
18  2019Q3  1237500.0   12
19  2019Q4  1455000.0   26
20  2020Q1  1468000.0   9

代码

x = dd2['qtr']


y1 = dd2['count']
y2 = dd2['median']



fig, ax = plt.subplots(figsize=(40,10))

ax = plt.subplot(111)
ax2 = ax.twinx()


y1_plot = y1.plot(ax=ax2, color='green', legend=True, marker='*', label="median")
y2_plot = y2.plot(ax=ax, color='red',   legend=True, linestyle='--', marker='x', label="count")


plt.title('Price trend analysis')
ax.set_xticklabels(x, rotation='vertical',color='k', size=20)

ax.set_xlabel('year')
ax.set_ylabel('sold price')
ax2.set_ylabel('number of sales')

y1_patch = mpatches.Patch(color='red', label='median sold price')
y2_patch = mpatches.Patch(color='green', label='count')
plt.legend(handles=[y2_patch,y1_patch],loc='upper right')


plt.savefig('chart.png', dpi=300,bbox_inches ='tight')
plt.show()

在此处输入图像描述

标签: pythonmatplotlib

解决方案


我不会使用 Pandas 的系列绘图方法,而是使用 pyplot 将您的 x 和 y 数据绘制在一起,如下所示:

# everything is the same up to 'ax2 = ax.twinx()'

# plot on your axes, save a reference to the line
line1 = ax.plot(x, y1, color="green", label="median sold price", marker='*')
line2 = ax2.plot(x, y2, color="red", label="count", marker='x')

# no need for messing with patches
lines = line1 + line2
labels = [l.get_label() for l in lines]
ax.legend(lines, labels, loc='upper right')

# this is the same as before again
plt.title('Price trend analysis')
ax.xaxis.set_tick_params(rotation=90, color='k', size
ax.set_xlabel('year')
ax.set_ylabel('sold price')
ax2.set_ylabel('number of sales')

plt.savefig('chart.png', dpi=300,bbox_inches ='tight')
plt.show()

推荐阅读