Bar plotting grouped Pandas

2024/10/15 19:26:30

I have a question regarding plotting grouped DataFrame data.

The data looks like:

data =index    taste    food0        good     cheese
1        bad      tomato
2        worse    tomato
3        worse    cheese
4        good     meat
5        good     meat
6        bad      cheese
7        worse    tomato
8        worse    tomato
9        good     cheese
10       worse    meat
11       good     meat

What I want to do is to have a bar plot having each taste category as x-axis (good, bad, worse) and the percentage distribution of each food-type within each taste category as bars.

So, looking at e.g. taste category worse we have: 3 tomato, 1 cheese and 1 meat. In total there are 3+1+1=5 food-types in the category, and hence:

3/5=60% tomato, 1/5=20% cheese and 1/5=20% meat

So far I have tried to use GroupBy and agg with something like:

df_1 = data.groupby(['taste', 'food']).agg({'taste' : 'count'})
df_2 = df_1.groupby(level=0).apply(lambda x: 100 * x / float(x.sum()))

which seems to yield my wanted result:

              taste
taste food         
bad   cheese   50.0tomato   50.0
good  cheese   40.0meat     60.0
worse cheese   20.0meat     20.0tomato   60.0

But now I am stuck on how to actually plot this!

In Excel, it would look something like:

enter image description here

Answer

I seem to have found an example:

making a stacked barchart in pandas

Sufficient doing:

df_3 = df_2.unstack()
df_3.plot(kind='bar',stacked=True, rot=1)
https://en.xdnf.cn/q/117798.html

Related Q&A

Nginx+bottle+uwsgi Server returning 404 on every request

I have setup an Nginx server with following configuration:server {listen 8080;server_name localhost;location / {include uwsgi_params;uwsgi_pass unix:/tmp/uwsgi.notesapi.socket;uwsgi_param UWSGI_PYHOME …

Checking multiple for items in a for loop python

Ive written a code to tell the user that the their brackets are not balanced.I can exactly tell where my code is going wrong.Once it comes across the first situation of brackets, it does not continue t…

Can I export pandas DataFrame to Excel stripping tzinfo?

I have a timezone aware TimeSeries in pandas 0.10.1. I want to export to Excel, but the timezone prevents the date from being recognized as a date in Excel.In [40]: resultado Out[40]: fecha_hora 2013-…

Converting kwargs into variables?

How do I convert kwargs objects into local variables? I am a math teacher and I want to write a helper function where I can use JS-style template strings to write problems.I want to do something like …

Maya Python: Unbound Method due to Reload()

I have two files that import the same object tracking method from a third file. It works something like thisfile TrackingMethodclass Tracker(object):def __init__(self,nodeName=None,dag=None,obj=None):#…

How to append to a table in BigQuery using Python BigQuery API

Ive been able to append/create a table from a Pandas dataframe using the pandas-gbq package. In particular using the to_gbq method. However, When I want to check the table using the BigQuery web UI I s…

Splitting values out of a CSV Reader Python

Here is my current code a_reader = None a_reader = open(data.csv, rU) a_csv_reader = csv.reader(a_reader)for row in a_csv_reader:print row a_reader.close()count = 0 sum = 0.0 a_reader = open(…

python - list variable not storing proper result in recursion

I am trying to store all possible parenthesisation of a list through recursion.Example: printRange(0,3) Answer will be [[0],[1], [2]], [[0], [1, 2]], [[0, 1], [2]], [[0, 1, 2]]I could get a right answe…

Embedding matplotlib canvas into tkinter GUI - plot is not showing up, but no error is thrown

Running the python python script below does not show the embedded matplotlib plot. However it also throws no error message. Upon running the script, it is supposed to display a GUI displaying 4 buttons…

Can I get rid of this b character in my print statement? [duplicate]

This question already has answers here:What does a b prefix before a python string mean?(2 answers)Closed 7 years ago.Im wondering what this b charcter is and why its appearing. Im also wondering if I…