Python Matplotlib x轴有限范围

Python Matplotlib x轴有限范围,python,matplotlib,Python,Matplotlib,所以我一直在尝试绘制一些数据。x轴限为两年。我的问题很简单,当可用数据介于2015Q1到2020Q1之间时,有人能解释为什么X轴仅限于2015Q1到2017Q1的日期范围吗。我的代码是否丢失或不正确 dd2 代码 使用mtick绘制所有x轴数据 import matplotlib.ticker as mtick ax.xaxis.set_major_locator(mtick.IndexLocator(base=1, offset=0)) 使用mtick绘制所有x轴数据 import ma

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

dd2

代码


使用mtick绘制所有x轴数据

import matplotlib.ticker as mtick

ax.xaxis.set_major_locator(mtick.IndexLocator(base=1, offset=0))


使用mtick绘制所有x轴数据

import matplotlib.ticker as mtick

ax.xaxis.set_major_locator(mtick.IndexLocator(base=1, offset=0))


我不会使用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()

我不会使用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()

很高兴看到你解决了你的问题。您能否只突出显示实现解决方案所需的代码部分?这将使其他人更容易找到答案。更好的解决方案是将x和y数据一起绘制,这样pyplot就可以确定XTick应该放在哪里:
ax.plot(x,y1)
ax1.plot(x,y2)
@Junuxx谢谢你提出了一个更好的解决方案,我对python和pandas都是新手。你能更具体地说明在哪里修改我的代码吗?很高兴看到你解决了你的问题。您能否只突出显示实现解决方案所需的代码部分?这将使其他人更容易找到答案。更好的解决方案是将x和y数据一起绘制,这样pyplot就可以确定XTick应该放在哪里:
ax.plot(x,y1)
ax1.plot(x,y2)
@Junuxx谢谢你提出了一个更好的解决方案,我对python和pandas都是新手。你能更具体地说明我的代码在哪里修改吗?当我用上面的代码绘制图表时,x轴限制在2018Q1-2019Q2,而不是2015Q1-2020Q1。@karweng:对,哎哟,这根本不是我想要做的。包括如我所述的x参数。当我使用上述代码绘制图表时,x轴限制为2018Q1-2019Q2,而不是2015Q1-2020Q1。@karweng:对,哎哟,我根本不打算这么做。包括我描述的x参数。