Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot Pandas DataFrame and plot side by side

There are options to have plots side by side, likewise for pandas dataframes. Is there a way to plot a pandas dataframe and a plot side by side?

This is the code I have so far, but the dataframe is distorted.


import pandas as pd
import matplotlib.pyplot as plt
from pandas.plotting import table

# sample data
d = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
     'jan': [4, 24, 31, 2, 3],
     'feb': [25, 94, 57, 62, 70],
     'march': [5, 43, 23, 23, 51]}
df = pd.DataFrame(d)
df['total'] = df.iloc[:, 1:].sum(axis=1)

plt.figure(figsize=(16,8))

# plot table
ax1 = plt.subplot(121)
plt.axis('off')
tbl = table(ax1, df, loc='center')
tbl.auto_set_font_size(False)
tbl.set_fontsize(14)

# pie chart
ax2 = plt.subplot(122, aspect='equal')
df.plot(kind='pie', y = 'total', ax=ax2, autopct='%1.1f%%', 
 startangle=90, shadow=False, labels=df['name'], legend = False, fontsize=14)


plt.show()

Side by Side

like image 506
dimitris_ps Avatar asked Jul 18 '26 20:07

dimitris_ps


1 Answers

It's pretty simple to do with plotly and make_subplots()

  • define a figure with appropriate specs argument
  • add_trace() which is tabular data from your data frame
  • add_trace() which is pie chart from your data frame
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

# sample data
d = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
     'jan': [4, 24, 31, 2, 3],
     'feb': [25, 94, 57, 62, 70],
     'march': [5, 43, 23, 23, 51]}
df = pd.DataFrame(d)
df['total'] = df.iloc[:, 1:].sum(axis=1)


fig = make_subplots(rows=1, cols=2, specs=[[{"type":"table"},{"type":"pie"}]])
fig = fig.add_trace(go.Table(cells={"values":df.T.values}, header={"values":df.columns}), row=1,col=1)
fig.add_trace(px.pie(df, names="name", values="total").data[0], row=1, col=2)

enter image description here

like image 70
Rob Raymond Avatar answered Jul 20 '26 09:07

Rob Raymond