1.画叠加柱状图。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
#设置分辨率
my_dpi = 96
#设置图的尺寸(480x480)
plt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)
#y轴已粗体显示
rc('font', weight='bold')
#设置棕色柱子的高度
bars1 = [12, 28, 1, 8, 22]
#设置中间柱子的高度
bars2 = [28, 7, 16, 4, 10]
#设置顶部柱子的高度
bars3 = [25, 3, 23, 25, 17]
bars = [40, 35, 17, 12, 32]
r = [0,1,2,3,4]
names = ['A','B','C','D','E']
barWidth = 1
#创建柱子
plt.bar(r, bars1, color='#7f6d5f', edgecolor='white', width=barWidth)
plt.bar(r, bars2, bottom=bars1, color='#557f2d', edgecolor='white', width=barWidth)
plt.bar(r, bars3, bottom=bars, color='#2d7f5e', edgecolor='white', width=barWidth)
plt.xticks(r, names, fontweight='bold')
plt.xlabel("group")
#保存图片
plt.savefig('#12_stacked_barplot.png')
#展示图片
plt.show()
2.分类条形图。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
#设置分辨率
my_dpi = 96
#设置图的尺寸(480x480)
plt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)
barWidth = 0.25
#设置柱子的高度
bars1 = [12, 30, 1, 8, 22]
bars2 = [28, 6, 16, 5, 10]
bars3 = [29, 3, 24, 25, 17]
r1 = np.arange(len(bars1))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]
#创建柱子
plt.bar(r1, bars1, color='#7f6d5f', width=barWidth, edgecolor='white', label='var1')
plt.bar(r2, bars2, color='#557f2d', width=barWidth, edgecolor='white', label='var2')
plt.bar(r3, bars3, color='#2d7f5e', width=barWidth, edgecolor='white', label='var3')
plt.xlabel('group', fontweight='bold')
#添加x轴名称
plt.xticks([r + barWidth for r in range(len(bars1))], ['A', 'B', 'C', 'D', 'E'])
#创建图例
plt.legend()
#保存图片
plt.savefig('#12_grouped_barplot.png')
#展示图片
plt.show()
3.叠加柱形图。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
#设置分辨率
my_dpi = 96
#设置图的尺寸(480x480)
plt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)
r = [0,1,2,3,4]
raw_data = {'greenBars': [20, 1.5, 7, 10, 5], 'orangeBars': [5, 15, 5, 10, 15],'blueBars': [2, 15, 18, 5, 10]}
df = pd.DataFrame(raw_data)
#创建总数
totals = [i+j+k for i,j,k in zip(df['greenBars'], df['orangeBars'], df['blueBars'])]
#创建百分比
greenBars = [i / j * 100 for i,j in zip(df['greenBars'], totals)]
orangeBars = [i / j * 100 for i,j in zip(df['orangeBars'], totals)]
blueBars = [i / j * 100 for i,j in zip(df['blueBars'], totals)]
barWidth = 0.85
names = ('A','B','C','D','E')
#创建柱子
plt.bar(r, greenBars, color='#b5ffb9', edgecolor='white', width=barWidth)
plt.bar(r, orangeBars, bottom=greenBars, color='#f9bc86', edgecolor='white', width=barWidth)
plt.bar(r, blueBars, bottom=[i+j for i,j in zip(greenBars, orangeBars)], color='#a3acff', edgecolor='white', width=barWidth)
plt.xticks(r, names)
plt.xlabel("group")
#保存图片
plt.savefig('#12_stacked_percent_barplot.png')
#展示图片
plt.show()
本博主新开公众号, 希望大家能扫码关注一下,十分感谢大家。
本文来自:https://github.com/holtzy/The-Python-Graph-Gallery/blob/master/PGG_notebook.py