Home > Blockchain >  Plot Bar and Line Charts from Pivot Table
Plot Bar and Line Charts from Pivot Table

Time:02-14

I'm trying to create a plot with bar and line charts together where each chart corresponds to a column from my pivot table.

I've seen several questions with the same problem as me but non of them helped me. I want my first column of the dataset as a bar chart and the second as a line chart, with a different scale.

Here's my code:

#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()

Although the bar chart appears, the line chart doesn't. Can anyone help?

CodePudding user response:

Here is an example to demonstrate one way to do it:

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()

Which outputs: enter image description here

CodePudding user response:

#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
plt.axhline(mediaperc_target1_anomes, color='g')
#line chart
gb_treino3.iloc[:,1].plot(linestyle='-', marker='o', use_index=False, ax=ax2,color='orange')

Output: Bar and line chart

  • Related