Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python matplotlib绘图,条形图和线形图之间的时间序列标签不规则_Python_Matplotlib_Plot_Graph - Fatal编程技术网

Python matplotlib绘图,条形图和线形图之间的时间序列标签不规则

Python matplotlib绘图,条形图和线形图之间的时间序列标签不规则,python,matplotlib,plot,graph,Python,Matplotlib,Plot,Graph,在通过pandas使用matplotlib创建条形图和线形图时,我遇到了一些不一致的行为。例如: import matplotlib.pyplot as plt import pandas as pd from pandas_datareader import data test_df = data.get_data_yahoo('AAPL', start='2015-10-01') test_df['Adj Close'].plot() 使用合理的x轴标签按预期打印: 但是,如果随后尝试

在通过pandas使用matplotlib创建条形图和线形图时,我遇到了一些不一致的行为。例如:

import matplotlib.pyplot as plt
import pandas as pd
from pandas_datareader import data

test_df = data.get_data_yahoo('AAPL', start='2015-10-01')
test_df['Adj Close'].plot()
使用合理的x轴标签按预期打印:

但是,如果随后尝试从与条形图相同的数据帧中绘制某些内容:

test_df['Volume'].plot(kind='bar')

x轴刻度标签不再自动显示


这是熊猫/matplotlib的预期行为吗?如何轻松地将条形图上的x轴记号标签校正为与上面的直线图中的标签相似?

您可以告诉matplotlib显示每N个标签:

# show every Nth label
locs, labels = plt.xticks()
N = 10
plt.xticks(locs[::N], test_df.index[::N].strftime('%Y-%m-%d'))

屈服


另一个选项是直接使用matplotlib:

import matplotlib.pyplot as plt
import pandas as pd
from pandas_datareader import data
import matplotlib.dates as mdates

df = data.get_data_yahoo('AAPL', start='2015-10-01')
fig, ax = plt.subplots(nrows=2, sharex=True)

ax[0].plot(df.index, df['Adj Close'])
ax[0].set_ylabel('price per share')

ax[1].bar(df.index, df['Volume']/10**6)
ax[1].xaxis.set_major_locator(mdates.MonthLocator(bymonthday=-1))
xfmt = mdates.DateFormatter('%B %d, %Y')
ax[1].xaxis.set_major_formatter(xfmt)
ax[1].set_ylabel('Volume (millions)')

# autorotate the xlabels
fig.autofmt_xdate()
plt.show()

谢谢,此外,是否可能只在x轴上绘制月份、年份(如2015年10月),以及如何使y轴可读?您希望y轴标签看起来如何?实际上可能是一样的,只是没有1e8和y轴标签中的收益比例(即数量(百万))?我添加了第二个示例,直接使用matplotlib。有趣的是,
sharex=True
适用于第二个示例,但不适用于使用pandas DataFrame.plot调用。
import matplotlib.pyplot as plt
import pandas as pd
from pandas_datareader import data
import matplotlib.dates as mdates

df = data.get_data_yahoo('AAPL', start='2015-10-01')
fig, ax = plt.subplots(nrows=2, sharex=True)

ax[0].plot(df.index, df['Adj Close'])
ax[0].set_ylabel('price per share')

ax[1].bar(df.index, df['Volume']/10**6)
ax[1].xaxis.set_major_locator(mdates.MonthLocator(bymonthday=-1))
xfmt = mdates.DateFormatter('%B %d, %Y')
ax[1].xaxis.set_major_formatter(xfmt)
ax[1].set_ylabel('Volume (millions)')

# autorotate the xlabels
fig.autofmt_xdate()
plt.show()