Matplotlib - Move labels into middle of pie chart











up vote
6
down vote

favorite
1












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


enter image description here










share|improve this question
























  • 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

















up vote
6
down vote

favorite
1












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


enter image description here










share|improve this question
























  • 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















up vote
6
down vote

favorite
1









up vote
6
down vote

favorite
1






1





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


enter image description here










share|improve this question















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


enter image description here







python pandas matplotlib pie-chart






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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




















  • 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














1 Answer
1






active

oldest

votes

















up vote
2
down vote



accepted










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:



enter image description here





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


enter image description here



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


enter image description here






share|improve this answer





















    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
    });


    }
    });














    draft saved

    draft discarded


















    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








    up vote
    2
    down vote



    accepted










    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:



    enter image description here





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


    enter image description here



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


    enter image description here






    share|improve this answer

























      up vote
      2
      down vote



      accepted










      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:



      enter image description here





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


      enter image description here



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


      enter image description here






      share|improve this answer























        up vote
        2
        down vote



        accepted







        up vote
        2
        down vote



        accepted






        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:



        enter image description here





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


        enter image description here



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


        enter image description here






        share|improve this answer












        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:



        enter image description here





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


        enter image description here



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


        enter image description here







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 10 at 17:03









        ALollz

        10.9k31334




        10.9k31334






























            draft saved

            draft discarded




















































            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.




            draft saved


            draft discarded














            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





















































            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







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()