[519]matplotlib(三)|python中用matplotlib绘制条形图

  • 带误差线的条形图
import matplotlib.pyplot as plt
 
# 输入数据
mean_values = [1, 2, 3]
variance = [0.2, 0.4, 0.5]
bar_labels = ['bar 1', 'bar 2', 'bar 3']
 
# 绘制图形
x_pos = list(range(len(bar_labels)))
plt.bar(x_pos, mean_values, yerr=variance, align='center', alpha=0.5)
 
plt.grid()
 
# 设置y轴高度
max_y = max(zip(mean_values, variance)) # returns a tuple, here: (3, 5)
plt.ylim([0, (max_y[0] + max_y[1]) * 1.1])
 
# 设置轴标签和标题
plt.ylabel('variable y')
plt.xticks(x_pos, bar_labels)
plt.title('Bar plot with error bars')
 
plt.show()
#plt.savefig('./my_plot.png')

[519]matplotlib(三)|python中用matplotlib绘制条形图_第1张图片

  • 带误差线的水平条形图
from matplotlib import pyplot as plt
import numpy as np
 
# 输入数据
mean_values = [1, 2, 3]
std_dev = [0.2, 0.4, 0.5]
bar_labels = ['bar 1', 'bar 2', 'bar 3']
 
fig = plt.figure(figsize=(8,6))
 
# 绘制条形图
y_pos = np.arange(len(mean_values))
y_pos = [x for x in y_pos]
plt.yticks(y_pos, bar_labels, fontsize=10)
plt.barh(y_pos, mean_values, xerr=std_dev,
         align='center', alpha=0.4, color='g')
 
# 标签
plt.xlabel('measurement x')
t = plt.title('Bar plot with standard deviation')
plt.ylim([-1,len(mean_values)+0.5])
plt.xlim([0, 4])
plt.grid()
 
plt.show()

[519]matplotlib(三)|python中用matplotlib绘制条形图_第2张图片

  • 背对背条形图绘制
from matplotlib import pyplot as plt
import numpy as np
 
# 输入数据
X1 = np.array([1, 2, 3])
X2 = np.array([2, 2, 3])
 
 
bar_labels = ['bar 1', 'bar 2', 'bar 3']
 
fig = plt.figure(figsize=(8,6))
 
# 绘制
y_pos = np.arange(len(X1))
y_pos = [x for x in y_pos]
plt.yticks(y_pos, bar_labels, fontsize=10)
 
 
plt.barh(y_pos, X1,
         align='center', alpha=0.4, color='g')
 
# 我们简单的取反,画第二个条形图
plt.barh(y_pos, -X2,
         align='center', alpha=0.4, color='b')
 
# 标签
plt.xlabel('measurement x')
t = plt.title('Bar plot with standard deviation')
plt.ylim([-1,len(X1)+0.1])
plt.xlim([-max(X2)-1, max(X1)+1])
plt.grid()
 
plt.show()

[519]matplotlib(三)|python中用matplotlib绘制条形图_第3张图片

  • 条形图群
import matplotlib.pyplot as plt
 
# 输入数据
green_data = [1, 2, 3]
blue_data = [3, 2, 1]
red_data = [2, 3, 3]
labels = ['group 1', 'group 2', 'group 3']
 
# 设置条形图的位置和宽度
pos = list(range(len(green_data)))
width = 0.2
 
# 绘制
fig, ax = plt.subplots(figsize=(8,6))
 
plt.bar(pos, green_data, width,
                 alpha=0.5,
                 color='g',
                 label=labels[0])
 
plt.bar([p + width for p in pos], blue_data, width,
                 alpha=0.5,
                 color='b',
                 label=labels[1])
 
plt.bar([p + width*2 for p in pos], red_data, width,
                 alpha=0.5,
                 color='r',
                 label=labels[2])
 
# 设置标签和距离
ax.set_ylabel('y-value')
ax.set_title('Grouped bar plot')
ax.set_xticks([p + 1.5 * width for p in pos])
ax.set_xticklabels(labels)
 
# 设置x,y轴限制
plt.xlim(min(pos)-width, max(pos)+width*4)
plt.ylim([0, max(green_data + blue_data + red_data) * 1.5])
 
# 绘制
plt.legend(['green', 'blue', 'red'], loc='upper left')
plt.grid()
plt.show()

[519]matplotlib(三)|python中用matplotlib绘制条形图_第4张图片

  • 叠加条形图
import matplotlib.pyplot as plt
 
blue_data = [100,120,140]
red_data = [150,120,190]
green_data = [80,70,90]
 
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,5))
 
bar_width = 0.5
 
# positions of the left bar-boundaries
bar_l = [i+1 for i in range(len(blue_data))]
 
# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(bar_width/2) for i in bar_l]
 
###################
## Absolute count
###################
 
ax1.bar(bar_l, blue_data, width=bar_width,
        label='blue data', alpha=0.5, color='b')
ax1.bar(bar_l, red_data, width=bar_width,
        bottom=blue_data, label='red data', alpha=0.5, color='r')
ax1.bar(bar_l, green_data, width=bar_width,
        bottom=[i+j for i,j in zip(blue_data,red_data)], label='green data', alpha=0.5, color='g')
 
plt.sca(ax1)
plt.xticks(tick_pos, ['category 1', 'category 2', 'category 3'])
 
ax1.set_ylabel("Count")
ax1.set_xlabel("")
plt.legend(loc='upper left')
plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width])
plt.grid()
 
# rotate axis labels
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
 
############
## Percent
############
 
totals = [i+j+k for i,j,k in zip(blue_data, red_data, green_data)]
blue_rel = [i / j * 100 for  i,j in zip(blue_data, totals)]
red_rel = [i / j * 100 for  i,j in zip(red_data, totals)]
green_rel = [i / j * 100 for  i,j in zip(green_data, totals)]
 
ax2.bar(bar_l, blue_rel,
        label='blue data', alpha=0.5, color='b', width=bar_width
        )
ax2.bar(bar_l, red_rel,
        bottom=blue_rel, label='red data', alpha=0.5, color='r', width=bar_width
        )
ax2.bar(bar_l, green_rel,
        bottom=[i+j for i,j in zip(blue_rel, red_rel)],
        label='green data', alpha=0.5, color='g', width=bar_width
        )
 
plt.sca(ax2)
plt.xticks(tick_pos, ['category 1', 'category 2', 'category 3'])
ax2.set_ylabel("Percentage")
ax2.set_xlabel("")
 
plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width])
plt.grid()
 
# rotate axis labels
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
 
plt.show()

[519]matplotlib(三)|python中用matplotlib绘制条形图_第5张图片

  • 带标签的条形图1
from matplotlib import pyplot as plt
import numpy as np
 
data = range(200, 225, 5)
 
bar_labels = ['a', 'b', 'c', 'd', 'e']
 
fig = plt.figure(figsize=(10,8))
 
# 画图
y_pos = np.arange(len(data))
plt.yticks(y_pos, bar_labels, fontsize=16)
bars = plt.barh(y_pos, data,
         align='center', alpha=0.4, color='g')
 
# 注释
 
for b,d in zip(bars, data):
    plt.text(b.get_width() + b.get_width()*0.08, b.get_y() + b.get_height()/2,
        '{0:.2%}'.format(d/min(data)),
        ha='center', va='bottom', fontsize=12)
 
plt.xlabel('X axis label', fontsize=14)
plt.ylabel('Y axis label', fontsize=14)
t = plt.title('Bar plot with plot labels/text', fontsize=18)
plt.ylim([-1,len(data)+0.5])
plt.vlines(min(data), -1, len(data)+0.5, linestyles='dashed')
plt.grid()
 
plt.show()

[519]matplotlib(三)|python中用matplotlib绘制条形图_第6张图片

  • 带标签的条形图2
import matplotlib.pyplot as plt
 
# 输入数据
mean_values = [1, 2, 3]
bar_labels = ['bar 1', 'bar 2', 'bar 3']
 
# 画条
x_pos = list(range(len(bar_labels)))
rects = plt.bar(x_pos, mean_values, align='center', alpha=0.5)
 
# 标签
def autolabel(rects):
    for ii,rect in enumerate(rects):
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, '%s'% (mean_values[ii]),
            ha='center', va='bottom')
autolabel(rects)
 
 
 
# 设置y轴高度
max_y = max(zip(mean_values, variance)) # returns a tuple, here: (3, 5)
plt.ylim([0, (max_y[0] + max_y[1]) * 1.1])
 
# 设置标题
plt.ylabel('variable y')
plt.xticks(x_pos, bar_labels)
plt.title('Bar plot with labels')
 
plt.show()
#plt.savefig('./my_plot.png')

[519]matplotlib(三)|python中用matplotlib绘制条形图_第7张图片

  • 带颜色色差的条形图
import matplotlib.pyplot as plt
import matplotlib.colors as col
import matplotlib.cm as cm
 
# 输入数据
mean_values = range(10,18)
x_pos = range(len(mean_values))
 
 
# 创建 colormap
cmap1 = cm.ScalarMappable(col.Normalize(min(mean_values), max(mean_values), cm.hot))
cmap2 = cm.ScalarMappable(col.Normalize(0, 20, cm.hot))
 
# 画条
plt.subplot(121)
plt.bar(x_pos, mean_values, align='center', alpha=0.5, color=cmap1.to_rgba(mean_values))
plt.ylim(0, max(mean_values) * 1.1)
 
plt.subplot(122)
plt.bar(x_pos, mean_values, align='center', alpha=0.5, color=cmap2.to_rgba(mean_values))
plt.ylim(0, max(mean_values) * 1.1)
 
plt.show()

[519]matplotlib(三)|python中用matplotlib绘制条形图_第8张图片

  • 带填充模式的条形图
import matplotlib.pyplot as plt
 
patterns = ('-', '+', 'x', '\', '*', 'o', 'O', '.')
 
fig = plt.gca()
 
# 输入数据
mean_values = range(1, len(patterns)+1)
 
# 画条
x_pos = list(range(len(mean_values)))
bars = plt.bar(x_pos,
               mean_values,
               align='center',
               color='white',
               )
 
# 设置填充模式
for bar, pattern in zip(bars, patterns):
     bar.set_hatch(pattern)
 
 
# 设置标签
fig.axes.get_yaxis().set_visible(False)
plt.ylim([0, max(mean_values) * 1.1])
plt.xticks(x_pos, patterns)
 
plt.show()

[519]matplotlib(三)|python中用matplotlib绘制条形图_第9张图片

来源:http://blog.topspeedsnail.com/archives/724#more-724

你可能感兴趣的:(数据分析)