为什么 matplotlib .plot(kind='bar') 绘图与 .plot() 如此不同

13s*_*en1 2 python matplotlib

这可能是一个非常愚蠢的问题,但是当使用 .plot() 绘制 Pandas DataFrame 时,它​​非常快并生成具有适当索引的图表。一旦我尝试将其更改为条形图,它似乎就失去了所有格式并且索引变得疯狂。为什么会这样呢?有没有一种简单的方法来绘制与折线图格式相同的条形图?

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame()
df['Date'] = pd.date_range(start='01/01/2012', end='31/12/2018')
df['Value'] = np.random.randint(low=5, high=100, size=len(df))
df.set_index('Date', inplace=True)

df.plot()
plt.show()

df.plot(kind='bar')
plt.show()
Run Code Online (Sandbox Code Playgroud)

df.plot()

df.plot(kind='bar'

更新:为了进行比较,如果我获取数据并将其放入 Excel,然后创建一个线图和一个条形图(“列”)图,它会立即转换该图并保留线图的轴标签。如果我尝试用 Python 生成许多(数千个)带有多年日常数据的条形图,这需要很长时间。在 Python 中是否有等效的方法来执行此 Excel 转换?

Excel 绘图

Imp*_*est 5

Pandas bar plots are categorical in nature; i.e. each bar is a separate category and those get their own label. Plotting numeric bar plots (in the same manner a line plots) is not currently possible with pandas.

In contrast matplotlib bar plots are numerical if the input data is numbers or dates. So

plt.bar(df.index, df["Value"])
Run Code Online (Sandbox Code Playgroud)

produces

在此输入图像描述

Note however that due to the fact that there are 2557 data points in your dataframe, distributed over only some hundreds of pixels, not all bars are actually plotted. Inversely spoken, if you want each bar to be shown, it needs to be one pixel wide in the final image. This means with 5% margins on each side your figure needs to be more than 2800 pixels wide, or a vector format.

So rather than showing daily data, maybe it makes sense to aggregate to monthly or quarterly data first.