我正在嘗試創建一個帶有條形圖和折線圖的圖,其中每個圖表對應于我的資料透視表中的一列。
我見過幾個和我有同樣問題的問題,但沒有一個對我有幫助。我希望我的資料集的第一列作為條形圖,第二列作為折線圖,具有不同的比例。
這是我的代碼:
#creatin my pivot table
gb_treino3=treino.pivot_table(index="ANO_MES", columns="TARGET", values='ID_PVC', aggfunc='count', margins=True)
gb_treino3['1(%)'] = gb_treino3[1] / gb_treino3['All'] * 100
gb_treino3.drop([0,'All'], inplace=True, axis=1)
gb_treino3.drop('All', inplace=True, axis=0)
#plotting
fig,ax=plt.subplots(figsize=(15,10))
#plt.rcParams["figure.figsize"]=[7.50,3.50]
plt.rcParams["figure.autolayout"]= True
ax1=gb_treino3.iloc[:,0].plot(kind='bar', color='orange')
gb_treino3.iloc[:,1].plot(secondary_y=TRUE,xlim=ax1.get_xlim())
plt.show()
雖然條形圖出現,但折線圖沒有出現。任何人都可以幫忙嗎?
uj5u.com熱心網友回復:
這是一個示例來演示一種方法:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame(
{
"year": [2015, 2016, 2017, 2018, 2019, 2020, 2021],
"col1": [20, 60, 10, 40, 20, 25, 10],
"col2": [80, 30, 15, 30, 40, 50, 20],
}
)
# plt.figure()
ax = df[['year', 'col1']].plot(x='year', linestyle='-', marker='o', use_index=False)
df[['year', 'col2']].plot(x='year', kind='bar', ax=ax, use_index=True)
plt.show()
哪個輸出:
uj5u.com熱心網友回復:
#creating my pivot table
gb_treino3=treino.pivot_table(index="ANO_MES", columns="TARGET", values='ID_PVC', aggfunc='count', margins=True)
gb_treino3['1(%)'] = gb_treino3[1] / gb_treino3['All'] * 100
gb_treino3.drop([0,'All'], inplace=True, axis=1)
gb_treino3.drop('All', inplace=True, axis=0)
#plotting
plt.figure(figsize=(10,8))
fig, ax1 = plt.subplots()
#bar chart
gb_treino3.plot.bar(y=1,ax=ax1,figsize=(18,6))
#second axis
ax2 = ax1.twinx()
#line chart with previously defined value mediaperc_target1_anomes
plt.axhline(mediaperc_target1_anomes, color='g')
#line chart
gb_treino3.iloc[:,1].plot(linestyle='-', marker='o', use_index=False, ax=ax2,color='orange')
輸出:
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424634.html
標籤:Python 熊猫 matplotlib 条形图 折线图