3

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

2
  • How would you be satisfied if the current output results could be improved? Is it to match the pie chart and table in terms of vertical size? Commented Jul 14, 2021 at 3:16
  • A couple of things. Have the pandas DataFrame render as it usually does when displayed by itself, and align with the graph Commented Jul 14, 2021 at 9:45

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.