考慮以下示例:
import pandas as pd
import matplotlib.pyplot as plt
dfa = pd.DataFrame({'time' : [pd.to_datetime('2021-01-01'),
pd.to_datetime('2021-01-01'),
pd.to_datetime('2021-01-02'),
pd.to_datetime('2021-01-02'),
pd.to_datetime('2021-01-03'),
pd.to_datetime('2021-01-03'),
],
'group' : ['a','b','a','b','a','b'],
'value' : [1,2,3,2,5,5]})
dfa
Out[266]:
time group value
0 2021-01-01 a 1
1 2021-01-01 b 2
2 2021-01-02 a 3
3 2021-01-02 b 2
4 2021-01-03 a 5
5 2021-01-03 b 5
dli = pd.DataFrame({'time' :[pd.to_datetime('2021-01-01'),
pd.to_datetime('2021-01-02'),
pd.to_datetime('2021-01-03')],
'value' : [100,200,50]})
dli
Out[267]:
time value
0 2021-01-01 100
1 2021-01-02 200
2 2021-01-03 50
我正在嘗試創建一個堆疊條形圖dfa,并使用dli. 問題是我下面的代碼使條形圖消失(盡管單獨繪制的圖表有效)。
fig, ax1 = plt.subplots(figsize=(12, 4))
ax2 = ax1.twinx()
dfa.set_index(['time','group']).unstack().plot.bar(stacked = True, ax = ax1)
dli.set_index('time').plot(ax = ax2, color = 'red',
linewidth = 4, secondary_y = True)

你能看出是什么問題嗎?例如,單行作業
dfa.set_index(['time','group']).unstack().plot.bar(stacked = True)

謝謝!
uj5u.com熱心網友回復:
嘗試:
# plot data
d = dfa.set_index(['time','group']).unstack().cumsum(1)
fig,ax = plt.subplots()
for c in d.columns[::-1]:
ax.bar(d.index, d[c], label=c)
ax.legend()
ax1 = ax.twinx()
ax1.plot(dli['time'], dli['value'], color='r', label='value')
ax1.legend(loc='upper right')
輸出:

uj5u.com熱心網友回復:
這是我試圖得到你想要的。由于某種原因,我無法將正確的 y 軸設為紅色并帶有標簽,我嘗試使用的代碼是折線圖繪圖部分下的第 2/3 行代碼。
# Create figure and axes
fig, ax1 = plt.subplots(figsize = (12, 10))
ax2 = ax1.twinx()
# Create x, y1, y2
x = dfa['time']
y1 = dfa.set_index(['time','group']).unstack()
y2 = dli['value']
# Plot stacked bar chart (left y-axis)
y1.plot.bar(stacked = True, ax = ax1)
ax1.set_xlabel('Date', fontsize = 14)
ax1.set_xticklabels(('2021-01-01', '2021-01-02', '2021-01-03'), rotation = 0)
ax1.set_ylabel('Value (Groups a & b)', color = 'orange', fontsize = 14)
ax1.tick_params(axis = 'y', rotation = 0, labelcolor = 'blue' )
ax1.legend(title='')#set bar chart legend title to blank
# Plot line chart (right y-axis)
y2.plot(secondary_y = True, color = 'red', linewidth = 4, label = 'value (no group)')
ax2.set_ylabel('Value (No Group)', color = 'red', fontsize = 14)
ax2.tick_params(axis = 'y', rotation = 0, labelcolor = 'red' )
# Show line chart legend
plt.legend()
plt.show();
組合堆積條形圖和折線圖
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/339355.html
標籤:Python 熊猫 matplotlib
