簡體   English   中英

如何從列表創建分組條形圖

[英]How to create a grouped bar plot from lists

  • 我試圖繪制一個條形圖,它比較了兩種不同情況下的幾個項目的數量。
  • 所需的輸出將是帶有 4+4 = 8 個條形的條形圖,它們彼此相鄰,指示每種情況下每種類型的數量。
  • 這是我寫的初始代碼,它沒有給出我的期望。 我該如何修改?
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()
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()

在此處輸入圖片說明

  • python 2.7嘗試以下操作
fig, ax = plt.subplots(figsize=(6, 4))
df.plot.bar(ax=ax, rot=0)
ax.set(ylabel='Values')
plt.show()

可以通過使此代碼適應您的問題來實現。

# 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(加上numpy.arange )。

如果您考慮一下,很容易正確放置酒吧組。

在此處輸入圖片說明

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM