import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
np.random.seed(0)
x = np.arange(5)
y = np.random.randint(-5,5,5)
#ncols 列数量,2列子图
fig,ax = plt.subplots(ncols=2)
#纵向条形图
v_bars = ax[0].bar(x,y,color='r')
#横向条形图
h_bars = ax[1].barh(x,y,color='b')
#加入一条直线
ax[0].axhline(0,color='grey',linewidth=2)
ax[1].axvline(0,color='grey',linewidth=2)
fig,ax=plt.subplots()
v_var = ax.bar(x,y,color='lightblue')
#不同区域用不同颜色
for bar,height in zip(v_var,y):
if height<0:
bar.set(edgecolor='darkred',color='green',linewidth=3)
#图像填充,面积图
x = np.random.randn(100).cumsum()
y = np.linspace(0,10,100)
fig,ax = plt.subplots()
ax.fill_between(x,y,color='lightblue')
x = np.linspace(0,10,200)
y1 = 2*x + 1
y2 = 3*x + 2
y_mean = 0.5 * x * np.cos(2 * x) + 2.5 * x +1.1
fig,ax = plt.subplots()
ax.plot(x,y1)
ax.plot(x,y2)
ax.plot(x,y_mean)
ax.fill_between(x,y1,y2,color='lightblue')
#误差棒
mean_values = [1,2,3]
variance = [0.2,0.4,0.5]
bar_label = ['bar1','bar2','bar3']
x_pos = list(range(len(bar_label)))
plt.bar(x_pos,mean_values,yerr=variance,alpha=0.3)
y_max = max(zip(mean_values,variance))
plt.ylim(0,y_max[0] + y_max[1] * 1.2)
plt.ylabel('varable y')
plt.xticks(x_pos,bar_label)
([,
,
],
)
#背靠背,条形图
x1 = np.array([1,2,3])
x2 = np.array([2,2,3])
bar_labels = ['bar1','bar2','bar3']
y_pos = np.arange(len(x1))
y_pos = [x for x in y_pos]
plt.barh(y_pos,x1,color='g',alpha=0.5)
plt.barh(y_pos,-x2,color='b',alpha = 0.5)
plt.xlim(-max(x2)-1,max(x1)+1)
plt.ylim(-1,len(x1)+1)
(-1, 4)
#分组条形图
green_data = [1,2,3]
blue_data = [3,2,1]
red_data = [2,3,3]
labels = ['group1','group2','group3']
width=0.2
pos = list(range(len(green_data)))
gif,ax = plt.subplots()
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],blue_data,width,alpha=0.5,color='r',label=labels[2])
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)
plt.vlines(min(data),-1,len(y_pos),linestyle=':')
for b,d in zip(bars,data):
plt.text(b.get_width()+b.get_width()*0.05,b.get_y() + b.get_height()/2 , '{0:.2%}'.format(d/min(data)))
mean_values = range(10,18)
x_pos = range(len(mean_values))
import matplotlib.colors as col
import matplotlib.cm as cm
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,color = cmap1.to_rgba(mean_values))
plt.subplot(122)
plt.bar(x_pos,mean_values,color = cmap2.to_rgba(mean_values))
patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.')
fig = plt.gca()
mean_value = range(1,len(patterns)+1)
x_pos = list(range(len(mean_value)))
bars = plt.bar(x_pos,mean_value,color='white')
for bar,pattern in zip(bars,patterns):
bar.set_hatch(pattern)