Python 如何重新创建熊猫数据框、线和条的绘图

Python 如何重新创建熊猫数据框、线和条的绘图,python,pandas,matplotlib,Python,Pandas,Matplotlib,在此之前,我成功地创建了以下绘图 现在我再次尝试创建这个情节,但没有成功。我记性不好 我试过了 ax = df_prog.plot(kind='bar') df_prog.plot(kind='line') 如中所述 但是,根据首先选择的是哪一个,条形还是直线,只显示一个,而不是两个都显示在同一个图形中。您需要将时间轴转换为字符串。然后你可以把它们画在一起 import pandas as pd import matplotlib.pyplot as plt df_prog = pd.Da

在此之前,我成功地创建了以下绘图

现在我再次尝试创建这个情节,但没有成功。我记性不好

我试过了

ax = df_prog.plot(kind='bar')
df_prog.plot(kind='line')
如中所述


但是,根据首先选择的是哪一个,条形还是直线,只显示一个,而不是两个都显示在同一个图形中。

您需要将时间轴转换为字符串。然后你可以把它们画在一起

import pandas as pd
import matplotlib.pyplot as plt

df_prog = pd.DataFrame({"Prognos tim": [2, 3, 3]})
df_prog.index = pd.date_range(start='2020-01-01 00', end='2020-01-01 02', freq='H')
df_prog.index = df_prog.index + pd.Timedelta(minutes=30)

_, ax = plt.subplots()
df_prog.index = df_prog.index.astype(str)
df_prog.plot(kind='line', linestyle='-', marker='o', color='r', ax=ax)
df_prog.plot(kind='bar', ax=ax)

plt.show()

您缺少中的
ax=ax
use\u index=False
参数。这将在与条形图相同的图中绘制直线,并防止直线图使用x轴的时间戳。相反,x轴单位将从零开始,就像条形图一样,以便线与条形对齐。不需要转换索引,也不需要matplotlib

import pandas as pd # v 1.1.3

# Create sample dataset
idx = pd.date_range(start='2020-01-01 00:30', periods=3, freq='60T')
df_prog = pd.DataFrame({"Prognos tim": [2, 3, 3]}, index=idx)

# Combine pandas line and bar plots
ax = df_prog.plot.bar(figsize=(8,5))
df_prog.plot(use_index=False, linestyle='-', marker='o', color='r', ax=ax)

# Format labels
ax.set_xticklabels([ts.strftime('%H:%M') for ts in df_prog.index])
ax.figure.autofmt_xdate(rotation=0, ha='center')


如果省略
use_index=False
参数,则条形图和直线图仍然绘制在同一个图形中,只是x限制被约束到您创建的第二个绘图中。例如,您可以在此处看到:

ax = df_prog.plot.bar(figsize=(8,5))
df_prog.plot(linestyle='-', marker='o', color='r', ax=ax) # plot line in bars plot
ax.set_xlim(-0.5,2.5); # the bars are here
# ax.set_xlim(26297300, 26297450); # the line is here, the values are pandas period units

这是熊猫的新变化吗?混合条形图和折线图要求x轴为字符串类型?
ax = df_prog.plot.bar(figsize=(8,5))
df_prog.plot(linestyle='-', marker='o', color='r', ax=ax) # plot line in bars plot
ax.set_xlim(-0.5,2.5); # the bars are here
# ax.set_xlim(26297300, 26297450); # the line is here, the values are pandas period units