Plotting multiple stacked bar graph given a pandas dataframe in Python

Plotting multiple stacked bar graph given a pandas dataframe in Python

By : Edward Bailey
Date : October 17 2020, 03:08 PM
this will help There are a few things that I would like to express in a bar chart and have no clue about doing it using basic graphing techniques in matplotlib. I have a dataframe which is shown below and would like to obtain a bar chart as described below. The x-axis is based on the the Type column of the dataframe and within a single bar, the different colors are based on the Name column and the size of the bar is defined by the Count number. The color of the different names need not to be the same across different types, as long as the colors within a single bar is different. , You can use pivot and then plot
code :
df.pivot('Type', 'Name', 'Count').plot(kind = 'bar', stacked = True,  color = ['b','g','orange','m', 'r'])
df.pivot('Type', 'Name', 'Count').sort_values(by = 'A', ascending = False, axis = 1)\
.plot(kind = 'bar', stacked = True, color = ['g','r','b','orange', 'm'])

Share : facebook icon twitter icon
plotting stacked barplots on a pandas dataframe

plotting stacked barplots on a pandas dataframe

Date : March 29 2020, 07:55 AM
With these it helps I've just implemented a stacked bar plot function in the git repository for pandas, will be part of the upcoming 0.7.3 release:
code :
In [7]: df
          a         b         c
0  0.425199  0.564161  0.727342
1  0.174849  0.071170  0.679178
2  0.224619  0.331846  0.468959
3  0.654766  0.189413  0.868011
4  0.617331  0.715088  0.387540
5  0.444001  0.069016  0.417990
6  0.203908  0.689652  0.227135
7  0.382930  0.874078  0.571042
8  0.658687  0.493955  0.245392
9  0.758986  0.385871  0.455357

In [8]: df.plot(kind='barh', stacked=True)
Plotting a pandas dataframe as stacked barchart with matplotlib. How to get rid of the overlapping?

Plotting a pandas dataframe as stacked barchart with matplotlib. How to get rid of the overlapping?

By : user4968244
Date : March 29 2020, 07:55 AM
will be helpful for those in need I havent got to any solution about this overlapping bars in the barchart, but I have found a Workaround that solves the problem for me.
Using a stackplot instead of barchart.
code :
   def plotResults(dfA):
    fig, (ax1,ax2) = plt.subplots(2, sharex=True, sharey=False)
    # Upper Chart
    # Linechart
    ax1.plot(dfA.index, dfA['LP1'], color='blue',alpha=0.7, label='LP1')
    # stackplot
    ax1.stackplot(dfA.index,dfA['b'],dfA['p'], label=['b', 'p'], colors=['green','red'] )   #stackplot labels do not show in Legend
    ax1.plot([], [], color='red', label='p', linewidth=10)      #dummy plots only to show labels in the legend
    ax1.plot([], [], color='green', label='b', linewidth=10)    #dummy plots only to show labels in the legend
    # Lower Chart - Residuals
    ax2.plot(dfA.index, dfA['Residual'], color='red',alpha=0.7, label='Residual')
Python Pandas: Plotting 100% stacked graph issue

Python Pandas: Plotting 100% stacked graph issue

By : Liu Jiechao
Date : March 29 2020, 07:55 AM
Does that help The easiest way is to make a pivot table with the values you care about. Try something like this:
code :
tps = df5.pivot_table(values=['Total_Products_Sold'], 

tps = tps.div(tps.sum(1), axis=0)
tps.plot(kind='bar', stacked=True)
Plotting multiple lines from columns of Dataframe (python/pandas)?

Plotting multiple lines from columns of Dataframe (python/pandas)?

By : Hareesh Singh
Date : March 29 2020, 07:55 AM
will help you You can use pandas.core.groupby.DataFrameGroupBy.plot
code :
In[1]: import pandas as pd

In[2]: import numpy as np

In[3]: dataset = pd.DataFrame({"Age": np.random.random_integers(1, 5, 100), "Wavelength": np.random.uniform(90, 100, 100), "Luminosity": np.random.random_integers(5, 15, 100) * 10})

In[4]: dataset.groupby("Age").plot(x="Wavelength", y="Luminosity", kind="scatter")
1    Axes(0.125,0.1;0.775x0.8)
2    Axes(0.125,0.1;0.775x0.8)
3    Axes(0.125,0.1;0.775x0.8)
4    Axes(0.125,0.1;0.775x0.8)
5    Axes(0.125,0.1;0.775x0.8)
dtype: object
Pandas dataframe | groupby plotting | stacked and side by side graph

Pandas dataframe | groupby plotting | stacked and side by side graph

By : user3529967
Date : March 29 2020, 07:55 AM
wish of those help I am coming from R ggplot2 background and, and bit confused in matplotlib plot
code :
import matplotlib.pyplot as plt

languages = ['en','cs','es', 'pt', 'hi', 'en', 'es', 'es']
counties = ['us','ch','sp', 'br', 'in', 'fr', 'ar', 'pr']
count = [32, 432,43,55,6,23,455,23]
df = pd.DataFrame({'language': languages,'county': counties, 'count' : count})

modified = {}
modified['language'] = np.unique(df.language)
country_count = []
total_count = []
for x in modified['language']:

modified['country_count'] = country_count
modified['total_count'] = total_count

mod_df = pd.DataFrame(modified)

ind = mod_df.language
width = 0.35 

p1 = plt.bar(ind,mod_df.total_count, width)
p2 = plt.bar(ind,mod_df.country_count, width,

plt.ylabel("Total count")
plt.legend((p1[0], p2[0]), ('Total Count', 'Country Count'))
  language  country_count  total_count
0       cs              1          432
1       en              2           55
2       es              3          521
3       hi              1            6
4       pt              1           55
Related Posts Related Posts :
  • Django - stop synchronisation between different variables based on filters on same object
  • Using python together with knitr
  • Difference between <type 'classobj'>, <type 'object'>?
  • what is top level module in Python?
  • Is there a query method or similar for pandas Series (pandas.Series.query())?
  • Deleting DataFrame row in Pandas where column value in list
  • Python Integer and String Using
  • Python requests: URL with percent character
  • Why ActionChains(driver).move_to_element(elem).click().perform() twice
  • Why is my code not compiling
  • How to equalize the size of two numpy arrays
  • Hive Server 2 error on python connect with hiveserver2
  • TypeError: argument 1 must have a "write" method
  • Python, read uart and post to MQTT, has extra spaces
  • test getting skipped in pytest
  • Python: from list to enumerated list to pass to lambda reduce function
  • f[1] raised exception TypeError: 'int' object is not subscriptable
  • how to make a random list in python3
  • Keeping Python from spacing after breaking a line when printing a List
  • Create a temporary table in python to join with a sql table
  • How to update a specific line in a file in python?
  • Google PubSub python client returning StatusCode.UNAVAILABLE
  • Error in regex substring match in a list in python
  • Pandas groupby() on one column and then sum on another
  • How to use multiple "or" in python code
  • spider = cls(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument '_job'
  • Python, Django LDAP: detecting Authentication failed reasoning
  • Is it good to define a function in a function python
  • Zeep : Need to convert this sample soap request
  • How to render a template and send a file simultaneously with flask
  • Create new column in dataframe with match values from other dataframe
  • Group the values using one column and return the one having max value in other column using pandas dataframe
  • Python3 tkinter analog gauge
  • How to display all the data which is groupby "Cause" from 1981 to 1992 in python pandas?
  • Scrape content in json format - Python
  • How to replace pandas columns with the same name in to another dataframe?
  • Trying to build a proxy with aiohttp
  • Compound interest calculator loops
  • how to create a raw string when it's last character is a `\` in python
  • Scrapy - how can I split the data in this table?
  • Making post requests in python
  • How can I manipulate shapes (colors) in PowerPoint using Python and win32com.client?
  • Get sorted output for os.walk()
  • Pandas Mapping Column
  • How to remove border of microsoft word in text image in opencv with python?
  • why not always use map if its faster than the rest (list comprehension, loop (various variants))?
  • Trying to download a directory with requests
  • Django Django model “doesn't declare an explicit app_label” because of project's init.py file
  • Comparing 2 arrays using numpy and allocating values to a third array
  • How to do change the recieved SQL output format, in python
  • Python: how to write binary data to the stdout so that bash script can use process substitution?
  • How to combine two lists to get a new list of the shape as mentioned in description
  • Run-time Complexity for two algorithms (Big O notation calculation)
  • Import of csv data rows and columns when specyfing delimiter
  • Error in texting automated message in whatsapp using python
  • Why my model work ok with test data from train_test_split while doesn't with the new data?
  • Python Networkx: How to "redraw" graph after every iteration?
  • How to read a large json in pandas?
  • Protobuf Message Constructor
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com