E_Coops
E_Coops

Reputation: 1

How to plot two pie charts side by side in python

I've got a bit of code already written but am having trouble presenting them so they are side by side as one figure. Code follows a read in dataset name DF. I have two separate codes to make the charts but want to combine them into one cell so they present side by side. Codes are as follows:


labels = 'Male', 'Female'
explode = (0, 0)

fig1, ax1 = plt.subplots()
ax1.pie(DF.sex.value_counts(), explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')
plt.show()




labels = "Has heart disease", "Doesn't have heart disease"
explode = (0, 0)

fig1, ax1 = plt.subplots()
ax1.pie(DF.target.value_counts(), explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')
plt.show()

Any help would be appreciated, thanks :)

Ive tried playing around with the subplot as im aware that's what I need to alter but cant get past error messages when doing this.

Upvotes: 0

Views: 407

Answers (2)

Prakash Dahal
Prakash Dahal

Reputation: 4875

You have to use rows and cols inside subplots()

labels1 = 'Male', 'Female'
explode = (0, 0)
labels2 = "Has heart disease", "Doesn't have heart disease"
explode = (0, 0)

fig1, ax1 = plt.subplots(1,2)
ax1[0].pie(DF.sex.value_counts(), explode=explode, labels=labels1, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1[1].pie(DF.target.value_counts(), explode=explode, labels=labels2, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1[0].axis('equal')
ax1[1].axis('equal')
plt.show()

Upvotes: 1

Guy
Guy

Reputation: 50809

plotly has a great guide for creating pie charts

import plotly.graph_objects as go
from plotly.subplots import make_subplots

gender = 'Male', 'Female'
disease = "Has heart disease", "Doesn't have heart disease"

fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'domain'}, {'type': 'domain'}]])
fig.add_trace(go.Pie(labels=gender, values=[42, 37]), 1, 1)
fig.add_trace(go.Pie(labels=disease, values=[27, 53]), 1, 2)
fig.show()

enter image description here

Upvotes: 0

Related Questions