PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 28, 2022

[FIXED] How to plot categorical variables with a pie chart

 November 28, 2022     dataframe, matplotlib, pandas, pie-chart, python     No comments   

Issue

I am concerned with a single column (fruit) from my df:

| fruit               |
| --------------------|  
| apple, orange       | 
| banana              |
| grapefruit, orange  |
| apple, banana, kiwi |

I want to plot the values from fruit to a pie chart to get a visual representation of the distribution of each individual fruit

I run: df.plot(kind='pie', y='fruit')

But this gives a TypeError: '<' not supported between instances of 'str' and 'int'

I have read: How can I read inputs as numbers?

But I can't see how it helps solve my problem

Any help much appreciated!


Solution

You can split and explode:

(df['fruit']
 .str.split(',\s*')
 .explode()
 .value_counts()
 .plot(kind='pie')
)

Output:

pie chart



Answered By - mozway
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing