柱状图(或条形图)是最常见的图类型之一。 它显示了数值变量和类别变量之间的关系。 (1)绘制基础柱状图
用python和matplotlib绘制的最基本的柱状图
%reset -f
%clear
# In[*]
import numpy as np
import matplotlib.pyplot as plt
# Make a fake dataset:
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(bars))
# Create bars
plt.bar(y_pos, height)
# Create names on the x-axis
plt.xticks(y_pos, bars)
# Show graphic
plt.show()
(2)绘制水平横放的柱状图
这里使用的是barh函数而不是bar函数
# libraries
import numpy as np
import matplotlib.pyplot as plt
# Make fake dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(bars))
# Create horizontal bars
plt.barh(y_pos, height)
# Create names on the y-axis
plt.yticks(y_pos, bars)
# Show graphic
plt.show()
(3)设置柱状图颜色
设置所有柱子均为相同的颜色
# libraries
import numpy as np
import matplotlib.pyplot as plt
# Make a fake dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(bars))
# RGB is a way of making colors. You have to to provide an amount of red,
# green and blue + the transparency and it returns a color.
plt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
plt.xticks(y_pos, bars)
plt.show()
(4)设置柱状图颜色
设置不同的柱子为特定的颜色
plt.bar(y_pos, height, color=['black', 'red', 'green', 'blue', 'cyan'])
plt.xticks(y_pos, bars)
plt.show()
(5)设置柱状图柱子的边缘颜色
plt.bar(y_pos, height, color=(0.1, 0.1, 0.1, 0.1), edgecolor='blue')
plt.xticks(y_pos, bars)
plt.show()
(6)设置柱状图的标题title
import numpy as np
import matplotlib.pyplot as plt
# Fake dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(bars))
# Create bars and choose color
plt.bar(y_pos, height, color = (0.5,0.1,0.5,0.6))
# Add title and axis names
plt.title('My title')
plt.xlabel('categories')
plt.ylabel('values')
# Limits for the Y axis
plt.ylim(0,60)
# Create names
plt.xticks(y_pos, bars)
# Show graphic
plt.show()
(7)设置柱状图的柱子之间的间隔
# library
import matplotlib.pyplot as plt
# Make fake dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
# Choose the position of each barplots on the x-axis (space=1,4,3,1)
y_pos = [0,1,5,8,9]
# Create bars
plt.bar(y_pos, height)
# Create names on the x-axis
plt.xticks(y_pos, bars)
# Show graphic
plt.show()
(8)设置柱状图的柱子的宽度
import matplotlib.pyplot as plt
# Make fake dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
# Choose the width of each bar and their positions
width = [0.1,0.2,3,1.5,0.3]
y_pos = [0,0.3,2,4.5,5.5]
# Make the plot
plt.bar(y_pos, height, width=width)
plt.xticks(y_pos, bars)
plt.show()
(9)设置柱状图的x、Y轴标题
# libraries
import numpy as np
import matplotlib.pyplot as plt
# Fake dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(bars))
# Create bars and choose color
plt.bar(y_pos, height, color = (0.5,0.1,0.5,0.6))
# Add title and axis names
plt.title('My title')
plt.xlabel('categories')
plt.ylabel('values')
# Limits for the Y axis
plt.ylim(0,60)
# Create names
plt.xticks(y_pos, bars)
# Show graphic
plt.show()
(10)设置柱状图的x、Y轴标题的颜色
# libraries
import numpy as np
import matplotlib.pyplot as plt
# Choose the height of the bars
height = [3, 12, 5, 18, 45]
# Choose the names of the bars
bars = ('group1', 'group2', 'group3', 'group4', 'group5')
y_pos = np.arange(len(bars))
# Create bars
plt.bar(y_pos, height)
# Create names on the x-axis
plt.xticks(y_pos, bars, color='orange')
plt.yticks(color='orange')
# Show graphic
plt.show()
(11)设置柱状图的x轴标题的字体大小
# libraries
import numpy as np
import matplotlib.pyplot as plt
# Create data
height = [3, 12, 5, 18, 45]
bars = ('A','B','C','D','E')
# Create bars
plt.bar(y_pos, height)
# Create names on the x-axis
plt.xticks(y_pos, bars)
plt.xlabel('category', fontweight='bold', color = 'orange', fontsize='18')
# Show graphic
plt.show()
(12)设置柱状图的x轴标题的的方向
# libraries
import numpy as np
import matplotlib.pyplot as plt
# Create data
height = [3, 12, 5, 18, 45]
bars = ("very long group name 1","very long group name 2","very long group name 3","very long group name 4","very long group name 5")
# Create bars
plt.bar(y_pos, height)
# Rotation of the bars names
plt.xticks(y_pos, bars, rotation=90)
# Custom the subplot layout
plt.subplots_adjust(bottom=0.4, top=0.99)
# Show graphic
plt.show()
(13)设置带有误差棒的柱状图
# libraries
import numpy as np
import matplotlib.pyplot as plt
# width of the bars
barWidth = 0.3
# Choose the height of the blue bars
bars1 = [10, 9, 2]
# Choose the height of the cyan bars
bars2 = [10.8, 9.5, 4.5]
# Choose the height of the error bars (bars1)
yer1 = [0.5, 0.4, 0.5]
# Choose the height of the error bars (bars2)
yer2 = [1, 0.7, 1]
# The x position of bars
r1 = np.arange(len(bars1))
r2 = [x + barWidth for x in r1]
# Create blue bars
plt.bar(r1, bars1, width = barWidth, color = 'blue', edgecolor = 'black', yerr=yer1, capsize=7, label='poacee')
# Create cyan bars
plt.bar(r2, bars2, width = barWidth, color = 'cyan', edgecolor = 'black', yerr=yer2, capsize=7, label='sorgho')
# general layout
plt.xticks([r + barWidth for r in range(len(bars1))], ['cond_A', 'cond_B', 'cond_C'])
plt.ylabel('height')
plt.legend()
# Show graphic
plt.show()
(14)设置带有亚组的柱状图
# library
import matplotlib.pyplot as plt
# Create bars
barWidth = 0.9
bars1 = [3, 3, 1]
bars2 = [4, 2, 3]
bars3 = [4, 6, 7, 10, 4, 4]
bars4 = bars1 + bars2 + bars3
# The X position of bars
r1 = [1,5,9]
r2 = [2,6,10]
r3 = [3,4,7,8,11,12]
r4 = r1 + r2 + r3
# Create barplot
plt.bar(r1, bars1, width = barWidth, color = (0.3,0.1,0.4,0.6), label='Alone')
plt.bar(r2, bars2, width = barWidth, color = (0.3,0.5,0.4,0.6), label='With Himself')
plt.bar(r3, bars3, width = barWidth, color = (0.3,0.9,0.4,0.6), label='With other genotype')
# Note: the barplot could be created easily. See the barplot section for other examples.
# Create legend
plt.legend()
# Text below each barplot with a rotation at 90°
plt.xticks([r + barWidth for r in range(len(r4))], ['DD', 'with himself', 'with DC', 'with Silur', 'DC', 'with himself', 'with DD', 'with Silur', 'Silur', 'with himself', 'with DD', 'with DC'], rotation=90)
# Create labels
label = ['n = 6', 'n = 25', 'n = 13', 'n = 36', 'n = 30', 'n = 11', 'n = 16', 'n = 37', 'n = 14', 'n = 4', 'n = 31', 'n = 34']
# Text on the top of each barplot
for i in range(len(r4)):
plt.text(x = r4[i]-0.5 , y = bars4[i]+0.1, s = label[i], size = 6)
# Adjust the margins
plt.subplots_adjust(bottom= 0.2, top = 0.98)
# Show graphic
plt.show()
(15)设置叠加柱状图stack plot
# libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
# y-axis in bold
rc('font', weight='bold')
# Values of each group
bars1 = [12, 28, 1, 8, 22]
bars2 = [28, 7, 16, 4, 10]
bars3 = [25, 3, 23, 25, 17]
# Heights of bars1 + bars2
bars = np.add(bars1, bars2).tolist()
# The position of the bars on the x-axis
r = [0,1,2,3,4]
# Names of group and bar width
names = ['A','B','C','D','E']
barWidth = 1
# Create brown bars
plt.bar(r, bars1, color='#7f6d5f', edgecolor='white', width=barWidth)
# Create green bars (middle), on top of the firs ones
plt.bar(r, bars2, bottom=bars1, color='#557f2d', edgecolor='white', width=barWidth)
# Create green bars (top)
plt.bar(r, bars3, bottom=bars, color='#2d7f5e', edgecolor='white', width=barWidth)
# Custom X axis
plt.xticks(r, names, fontweight='bold')
plt.xlabel("group")
# Show graphic
plt.show()
(16)设置叠加柱状图stack plot
# libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
# Data
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)
# From raw value to percentage
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)]
# plot
barWidth = 0.85
names = ('A','B','C','D','E')
# Create green Bars
plt.bar(r, greenBars, color='#b5ffb9', edgecolor='white', width=barWidth)
# Create orange Bars
plt.bar(r, orangeBars, bottom=greenBars, color='#f9bc86', edgecolor='white', width=barWidth)
# Create blue Bars
plt.bar(r, blueBars, bottom=[i+j for i,j in zip(greenBars, orangeBars)], color='#a3acff', edgecolor='white', width=barWidth)
# Custom x axis
plt.xticks(r, names)
plt.xlabel("group")
# Show graphic
plt.show()
image.png
(17)设置叠加柱状图stack plot(百分比)
# Create green Bars
plt.bar(r, greenBars, color='#b5ffb9', edgecolor='white', width=barWidth, label="group A")
# Create orange Bars
plt.bar(r, orangeBars, bottom=greenBars, color='#f9bc86', edgecolor='white', width=barWidth, label="group B")
# Create blue Bars
plt.bar(r, blueBars, bottom=[i+j for i,j in zip(greenBars, orangeBars)], color='#a3acff', edgecolor='white', width=barWidth, label="group C")
# Custom x axis
plt.xticks(r, names)
plt.xlabel("group")
# Add a legend
plt.legend(loc='upper left', bbox_to_anchor=(1,1), ncol=1)
# Show graphic
plt.show()