Matplotlib - Move labels into middle of pie chart
I've got my pie chart working but I noticed that the text boxes for the actual chart doesn't seem to be working correctly. They are just clustered so I was wondering is there any way for me to move the labels into the middle where the white circle is and have the matching colour beside it or not?
crimeTypes = dict(crimeData["Crime type"].value_counts())
crimeType =
totalAmount =
numberOfCrimes = 14
for key in sorted(crimeTypes, key=crimeTypes.get, reverse=True):
crimeType.append(key)
totalAmount.append(crimeTypes.get(key))
crimeType_sample = crimeType[0:numberOfCrimes]
totalAmount_sample = totalAmount[0:numberOfCrimes]
fig1, ax1 = plt.subplots()
ax1.pie(totalAmount_sample, labels=crimeType_sample, autopct='%1.1f%%', shadow=False, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(10,10)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.show();
python pandas matplotlib pie-chart
add a comment |
I've got my pie chart working but I noticed that the text boxes for the actual chart doesn't seem to be working correctly. They are just clustered so I was wondering is there any way for me to move the labels into the middle where the white circle is and have the matching colour beside it or not?
crimeTypes = dict(crimeData["Crime type"].value_counts())
crimeType =
totalAmount =
numberOfCrimes = 14
for key in sorted(crimeTypes, key=crimeTypes.get, reverse=True):
crimeType.append(key)
totalAmount.append(crimeTypes.get(key))
crimeType_sample = crimeType[0:numberOfCrimes]
totalAmount_sample = totalAmount[0:numberOfCrimes]
fig1, ax1 = plt.subplots()
ax1.pie(totalAmount_sample, labels=crimeType_sample, autopct='%1.1f%%', shadow=False, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(10,10)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.show();
python pandas matplotlib pie-chart
I'm gonna drop pandas from the title because it's a matplotlib issue, but nice question :)
– roganjosh
Nov 10 at 14:07
No worries, sorry about that, wasn't too sure which thing I had to add!
– ComSci Student
Nov 10 at 14:09
3
Don't be sorry, it's a refreshing question from a new user. I have a feeling I know who can/will answer this (I can't) but if you can include data to make a repeatable example for them to test with, even better. Doesn't have to be your real data, just a minimal example.
– roganjosh
Nov 10 at 14:12
add a comment |
I've got my pie chart working but I noticed that the text boxes for the actual chart doesn't seem to be working correctly. They are just clustered so I was wondering is there any way for me to move the labels into the middle where the white circle is and have the matching colour beside it or not?
crimeTypes = dict(crimeData["Crime type"].value_counts())
crimeType =
totalAmount =
numberOfCrimes = 14
for key in sorted(crimeTypes, key=crimeTypes.get, reverse=True):
crimeType.append(key)
totalAmount.append(crimeTypes.get(key))
crimeType_sample = crimeType[0:numberOfCrimes]
totalAmount_sample = totalAmount[0:numberOfCrimes]
fig1, ax1 = plt.subplots()
ax1.pie(totalAmount_sample, labels=crimeType_sample, autopct='%1.1f%%', shadow=False, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(10,10)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.show();
python pandas matplotlib pie-chart
I've got my pie chart working but I noticed that the text boxes for the actual chart doesn't seem to be working correctly. They are just clustered so I was wondering is there any way for me to move the labels into the middle where the white circle is and have the matching colour beside it or not?
crimeTypes = dict(crimeData["Crime type"].value_counts())
crimeType =
totalAmount =
numberOfCrimes = 14
for key in sorted(crimeTypes, key=crimeTypes.get, reverse=True):
crimeType.append(key)
totalAmount.append(crimeTypes.get(key))
crimeType_sample = crimeType[0:numberOfCrimes]
totalAmount_sample = totalAmount[0:numberOfCrimes]
fig1, ax1 = plt.subplots()
ax1.pie(totalAmount_sample, labels=crimeType_sample, autopct='%1.1f%%', shadow=False, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(10,10)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.show();
python pandas matplotlib pie-chart
python pandas matplotlib pie-chart
edited Nov 10 at 14:09
asked Nov 10 at 14:03
ComSci Student
433
433
I'm gonna drop pandas from the title because it's a matplotlib issue, but nice question :)
– roganjosh
Nov 10 at 14:07
No worries, sorry about that, wasn't too sure which thing I had to add!
– ComSci Student
Nov 10 at 14:09
3
Don't be sorry, it's a refreshing question from a new user. I have a feeling I know who can/will answer this (I can't) but if you can include data to make a repeatable example for them to test with, even better. Doesn't have to be your real data, just a minimal example.
– roganjosh
Nov 10 at 14:12
add a comment |
I'm gonna drop pandas from the title because it's a matplotlib issue, but nice question :)
– roganjosh
Nov 10 at 14:07
No worries, sorry about that, wasn't too sure which thing I had to add!
– ComSci Student
Nov 10 at 14:09
3
Don't be sorry, it's a refreshing question from a new user. I have a feeling I know who can/will answer this (I can't) but if you can include data to make a repeatable example for them to test with, even better. Doesn't have to be your real data, just a minimal example.
– roganjosh
Nov 10 at 14:12
I'm gonna drop pandas from the title because it's a matplotlib issue, but nice question :)
– roganjosh
Nov 10 at 14:07
I'm gonna drop pandas from the title because it's a matplotlib issue, but nice question :)
– roganjosh
Nov 10 at 14:07
No worries, sorry about that, wasn't too sure which thing I had to add!
– ComSci Student
Nov 10 at 14:09
No worries, sorry about that, wasn't too sure which thing I had to add!
– ComSci Student
Nov 10 at 14:09
3
3
Don't be sorry, it's a refreshing question from a new user. I have a feeling I know who can/will answer this (I can't) but if you can include data to make a repeatable example for them to test with, even better. Doesn't have to be your real data, just a minimal example.
– roganjosh
Nov 10 at 14:12
Don't be sorry, it's a refreshing question from a new user. I have a feeling I know who can/will answer this (I can't) but if you can include data to make a repeatable example for them to test with, even better. Doesn't have to be your real data, just a minimal example.
– roganjosh
Nov 10 at 14:12
add a comment |
1 Answer
1
active
oldest
votes
Here's some sample data to reproduce your problem:
Sample Data:
import pandas as pd
data = (['Burglary']*50 + ['Arson', 'Theft', 'Violence'] + ['Drugs']*10 + ['Other'] +
['Shoplifting']*4 + ['Harassment']*17 + ['Murder', 'Vehicle Crime']*3 +
['Some other Crimes']*12 + ['Even More Crime', 'And Crime', 'And More Crime']*10)
crimeData = pd.DataFrame(data, columns=['Crime type'])
Which will result in this plot:
Use a legend
Do not plot the percentages or labels when you plot, and then create a legend which is placed off to the side:
fig1, ax1 = plt.subplots()
ax1.pie(totalAmount_sample, shadow=False, startangle=90) # No labels or %s
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(5,5)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.legend(labels=[f'{x} {np.round(y/sum(totalAmount_sample)*100,1)}%' for x,y in crimeTypes.items()],
bbox_to_anchor=(1,1))
plt.show();
Rotate the labels:
Create your labels and use rotatelabels=True
. Though this may still appear cramped in many cases.
fig1, ax1 = plt.subplots()
labels=[f'{x} {np.round(y/sum(totalAmount_sample)*100,1)}%' for x,y in crimeTypes.items()]
ax1.pie(totalAmount_sample, labels=labels, shadow=False, startangle=90,
rotatelabels=True) # No %
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(7,7)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.show();
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239733%2fmatplotlib-move-labels-into-middle-of-pie-chart%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here's some sample data to reproduce your problem:
Sample Data:
import pandas as pd
data = (['Burglary']*50 + ['Arson', 'Theft', 'Violence'] + ['Drugs']*10 + ['Other'] +
['Shoplifting']*4 + ['Harassment']*17 + ['Murder', 'Vehicle Crime']*3 +
['Some other Crimes']*12 + ['Even More Crime', 'And Crime', 'And More Crime']*10)
crimeData = pd.DataFrame(data, columns=['Crime type'])
Which will result in this plot:
Use a legend
Do not plot the percentages or labels when you plot, and then create a legend which is placed off to the side:
fig1, ax1 = plt.subplots()
ax1.pie(totalAmount_sample, shadow=False, startangle=90) # No labels or %s
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(5,5)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.legend(labels=[f'{x} {np.round(y/sum(totalAmount_sample)*100,1)}%' for x,y in crimeTypes.items()],
bbox_to_anchor=(1,1))
plt.show();
Rotate the labels:
Create your labels and use rotatelabels=True
. Though this may still appear cramped in many cases.
fig1, ax1 = plt.subplots()
labels=[f'{x} {np.round(y/sum(totalAmount_sample)*100,1)}%' for x,y in crimeTypes.items()]
ax1.pie(totalAmount_sample, labels=labels, shadow=False, startangle=90,
rotatelabels=True) # No %
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(7,7)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.show();
add a comment |
Here's some sample data to reproduce your problem:
Sample Data:
import pandas as pd
data = (['Burglary']*50 + ['Arson', 'Theft', 'Violence'] + ['Drugs']*10 + ['Other'] +
['Shoplifting']*4 + ['Harassment']*17 + ['Murder', 'Vehicle Crime']*3 +
['Some other Crimes']*12 + ['Even More Crime', 'And Crime', 'And More Crime']*10)
crimeData = pd.DataFrame(data, columns=['Crime type'])
Which will result in this plot:
Use a legend
Do not plot the percentages or labels when you plot, and then create a legend which is placed off to the side:
fig1, ax1 = plt.subplots()
ax1.pie(totalAmount_sample, shadow=False, startangle=90) # No labels or %s
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(5,5)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.legend(labels=[f'{x} {np.round(y/sum(totalAmount_sample)*100,1)}%' for x,y in crimeTypes.items()],
bbox_to_anchor=(1,1))
plt.show();
Rotate the labels:
Create your labels and use rotatelabels=True
. Though this may still appear cramped in many cases.
fig1, ax1 = plt.subplots()
labels=[f'{x} {np.round(y/sum(totalAmount_sample)*100,1)}%' for x,y in crimeTypes.items()]
ax1.pie(totalAmount_sample, labels=labels, shadow=False, startangle=90,
rotatelabels=True) # No %
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(7,7)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.show();
add a comment |
Here's some sample data to reproduce your problem:
Sample Data:
import pandas as pd
data = (['Burglary']*50 + ['Arson', 'Theft', 'Violence'] + ['Drugs']*10 + ['Other'] +
['Shoplifting']*4 + ['Harassment']*17 + ['Murder', 'Vehicle Crime']*3 +
['Some other Crimes']*12 + ['Even More Crime', 'And Crime', 'And More Crime']*10)
crimeData = pd.DataFrame(data, columns=['Crime type'])
Which will result in this plot:
Use a legend
Do not plot the percentages or labels when you plot, and then create a legend which is placed off to the side:
fig1, ax1 = plt.subplots()
ax1.pie(totalAmount_sample, shadow=False, startangle=90) # No labels or %s
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(5,5)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.legend(labels=[f'{x} {np.round(y/sum(totalAmount_sample)*100,1)}%' for x,y in crimeTypes.items()],
bbox_to_anchor=(1,1))
plt.show();
Rotate the labels:
Create your labels and use rotatelabels=True
. Though this may still appear cramped in many cases.
fig1, ax1 = plt.subplots()
labels=[f'{x} {np.round(y/sum(totalAmount_sample)*100,1)}%' for x,y in crimeTypes.items()]
ax1.pie(totalAmount_sample, labels=labels, shadow=False, startangle=90,
rotatelabels=True) # No %
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(7,7)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.show();
Here's some sample data to reproduce your problem:
Sample Data:
import pandas as pd
data = (['Burglary']*50 + ['Arson', 'Theft', 'Violence'] + ['Drugs']*10 + ['Other'] +
['Shoplifting']*4 + ['Harassment']*17 + ['Murder', 'Vehicle Crime']*3 +
['Some other Crimes']*12 + ['Even More Crime', 'And Crime', 'And More Crime']*10)
crimeData = pd.DataFrame(data, columns=['Crime type'])
Which will result in this plot:
Use a legend
Do not plot the percentages or labels when you plot, and then create a legend which is placed off to the side:
fig1, ax1 = plt.subplots()
ax1.pie(totalAmount_sample, shadow=False, startangle=90) # No labels or %s
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(5,5)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.legend(labels=[f'{x} {np.round(y/sum(totalAmount_sample)*100,1)}%' for x,y in crimeTypes.items()],
bbox_to_anchor=(1,1))
plt.show();
Rotate the labels:
Create your labels and use rotatelabels=True
. Though this may still appear cramped in many cases.
fig1, ax1 = plt.subplots()
labels=[f'{x} {np.round(y/sum(totalAmount_sample)*100,1)}%' for x,y in crimeTypes.items()]
ax1.pie(totalAmount_sample, labels=labels, shadow=False, startangle=90,
rotatelabels=True) # No %
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(7,7)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.show();
answered Nov 10 at 17:03
ALollz
11k31334
11k31334
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239733%2fmatplotlib-move-labels-into-middle-of-pie-chart%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I'm gonna drop pandas from the title because it's a matplotlib issue, but nice question :)
– roganjosh
Nov 10 at 14:07
No worries, sorry about that, wasn't too sure which thing I had to add!
– ComSci Student
Nov 10 at 14:09
3
Don't be sorry, it's a refreshing question from a new user. I have a feeling I know who can/will answer this (I can't) but if you can include data to make a repeatable example for them to test with, even better. Doesn't have to be your real data, just a minimal example.
– roganjosh
Nov 10 at 14:12