简体   繁体   中英

How to create a grouped bar plot from lists

  • I'm attempting to plot a bar plot, which compares the number of several items in 2 different cases.
  • The desired output would be a bar plot with 4+4 = 8 bars, next to to each other which indicates the number of each type for each case.
  • This is the initial code which I wrote, it is not giving what I expect. How can I modify this?
import numpy
import matplotlib.pyplot as plt

names = ["a","b","c","d"]
case1 = [5,7,5,6]
case2 = [7,4,8,5]

plt.hist(case1)
plt.show()
  • The simplest way is to create a dataframe with pandas, and then plot with pandas.DataFrame.plot
    • The dataframe index, 'names' in this case, is automatically used for the xaxis and the columns are plotted as bars.
    • matplotlib is used as the plotting backend
  • Tested in python 3.8 , pandas 1.3.1 and matplotlib 3.4.2
  • For lists of uneven length, see How to create a grouped bar plot from lists of uneven length
import pandas as pd
import matplotlib.pyplot as plt

names = ["a","b","c","d"]
case1 = [5,7,5,6]
case2 = [7,4,8,5]

# create the dataframe
df = pd.DataFrame({'c1': case1, 'c2': case2}, index=names)

# display(df)
   c1  c2
a   5   7
b   7   4
c   5   8
d   6   5

# plot
ax = df.plot(kind='bar', figsize=(6, 4), rot=0, title='Case Comparison', ylabel='Values')
plt.show()

在此处输入图片说明

  • Try the following for python 2.7
fig, ax = plt.subplots(figsize=(6, 4))
df.plot.bar(ax=ax, rot=0)
ax.set(ylabel='Values')
plt.show()

It can be achieved by adapting this code to your problem.

# importing pandas library
import pandas as pd
# import matplotlib library
import matplotlib.pyplot as plt
  
# creating dataframe
df = pd.DataFrame({
    'Names': ["a","b","c","d"],
    'Case1': [5,7,5,6],
    'Case2': [7,4,8,5]
})
  
# plotting graph
df.plot(x="Names", y=["Case1", "Case2"], kind="bar")

Matplotlib only (plus numpy.arange ).

It's easy to place correctly the bar groups if you think about it.

在此处输入图片说明

import matplotlib.pyplot as plt
from numpy import arange

places = ["Nujiang Lisu","Chuxiong Yi","Liangshan Yi","Dehong Dai & Jingpo"]
animals = ['Pandas', 'Snow Leopards']

n_places = len(places)
n_animals = len(animals)

animals_in_place = [[5,7,5,6],[7,4,8,5]]

### prepare for grouping the bars    
total_width = 0.5 # 0 ≤ total_width ≤ 1
d = 0.1 # gap between bars, as a fraction of the bar width, 0 ≤ d ≤ ∞
width = total_width/(n_animals+(n_animals-1)*d)
offset = -total_width/2

### plot    
x = arange(n_places)
fig, ax = plt.subplots()
for animal, data in zip(animals, animals_in_place):
    ax.bar(x+offset, data, width, align='edge', label=animal)
    offset += (1+d)*width
ax.set_xticks(x) ; ax.set_xticklabels(places)
fig.legend()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM