我正在尝试将条形图和折线图结合起来,但我似乎无法弄清楚。我尝试了代码here https://stackoverflow.com/questions/23482201/plot-pandas-dataframe-as-bar-and-line-on-the-same-one-chart但没有揭晓。我有以下代码和数据框:
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import matplotlib
matplotlib.style.use('ggplot')
%matplotlib inline
dates = pd.date_range('2017-09-16',periods=11)
df = pd.DataFrame({'Elektra_Cost': pd.Series([1.483393,
1.483393,
1.483393,
1.481280,
1.470714,
1.470714,
1.470714,
1.506829,
1.677233,
1.721489,
1.766318], index=dates, dtype='float64'),
'Gas_Cost': pd.Series([0.82122857,
0.82122857,
0.82122857,
0.85281429,
1.01074286,
1.01074286,
1.01074286,
0.92651429,
1.04047059,
1.50217941,
0.58479348],index=dates,dtype='float64'),
'TG10': pd.Series([10.3,
11.0,
11.3,
12.0,
13.0,
13.1,
12.8,
11.1,
13.5,
14.1,
13.3],index=dates,dtype='float64'),
'TN10': pd.Series([5.8,
4.3,
9.0,
7.5,
8.2,
7.9,
6.0,
4.3,
4.6,
8.5,
8.8],index=dates,dtype='float64'),
'TX10': pd.Series([15.7,
17.3,
15.4,
17.3,
18.5,
19.2,
20.0,
18.2,
20.6,
18.9,
18.2],index=dates,dtype='float64'),
})
然后我尝试绘制这样的图表:
ax = df[['TG10', 'TN10', 'TX10']].plot(figsize=(20,15), linestyle='--', secondary_y=['TG10', 'TN10', 'TX10'])
df[['Elektra_Cost', 'Gas_Cost']].plot(figsize=(20,15), kind='bar', ax=ax)
plt.show()
结果如下图所示:
plot https://i.stack.imgur.com/X2gGp.png
知道为什么我在图表中看不到线条(TG10、TN10 和 TX10)吗?
我在 jupyter 笔记本中运行这个
Update:
第一个建议的link https://stackoverflow.com/questions/19941685/how-to-show-a-bar-and-line-graph-on-the-same-plot成功了。所以我最终这样做了:
fig = plt.figure()
ax = df[['Elektra_Cost', 'Gas_Cost']].plot(figsize=(20,15), kind='bar')
plt.xticks(rotation=0)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), df[['TG10','TN10', 'TX10']], marker='o')
plt.show()
结果是:
plot https://i.stack.imgur.com/DJss6.jpg