多序列条形图
- 方法一:用多个条形图的函数
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
index = np.arange(4)
data1 = [1,5,6,3]
data2 = [1,2,3,5]
data3 = [4,8,9,4]
a = 0.3 #将一个空间分为3部分,a=0.3,3个占0.9,剩余0.1的空格
plt.title('multi bar chart')
plt.bar(index, # 条形图所在下标
data1, a, color = 'pink', label = 'a')
plt.bar(index+a,
data2, a, color = 'c', label = 'b')
plt.bar(index+2*a,
data3, a, color = 'orange', alpha = 0.5,label = 'c')
plt.legend()
同样可以画横向的多序列条形图
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
index = np.arange(4)
data1 = [1,5,6,3]
data2 = [1,2,3,5]
data3 = [4,8,9,4]
a = 0.3 #将一个空间分为3部分,a=0.3,3个占0.9,剩余0.1的空格
plt.title('multi bar chart')
plt.barh(index, # 条形图所在下标
data1, a, color = 'pink', label = 'a',hatch = '/')
plt.barh(index+a,
data2, a, color = 'c', label = 'b')
plt.barh(index+2*a,
data3, a, color = 'orange', alpha = 0.5,label = 'c')
plt.legend()
- 方法二:用DataFrame生成多序列条形图
import pandas as pd
%pylab inline
colors = ['pink','orange','c']
df = pd.DataFrame([[4,8,2],[1,5,3],[2,5,4]])
df.plot(kind = 'bar',color = colors)
同样的我们可以画横向的条形图、折线图等
import pandas as pd
%pylab inline
colors = ['pink','orange','c']
df = pd.DataFrame([[4,8,2],[1,5,3],[2,5,4]])
df.plot(kind = 'barh',color = colors)
堆叠条形图
由于要用到列表相加,所以我们需要ndarray的列表来进行叠加
#堆叠条形图
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
index = np.arange(4)
data1 = np.array([1,5,6,3])
data2 = np.array([1,2,1,5])
data3 = np.array([4,8,9,4])
a = 0.3
plt.title('multi bar chart')
plt.bar(index, data1, a, color = 'pink', label = 'a', hatch = '/')
plt.bar(index, data2, a, bottom = data1, # 堆叠在第一个上方
color = 'c', label = 'b')
plt.bar(index, data3, a, bottom = (data1 + data2), # 堆叠在第一个和第二个上方
color = 'orange', alpha = 0.5,label = 'c')
plt.legend()
同样的,横向的堆叠图改为plt.barh()
但参数bottom要改为left
#堆叠条形图
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
index = np.arange(4)
data1 = np.array([1,5,6,3])
data2 = np.array([1,2,1,5])
data3 = np.array([4,8,9,4])
a = 0.3
plt.title('multi bar chart')
plt.barh(index, data1, a, color = 'pink', label = 'a', hatch = '/')
plt.barh(index, data2, a, left = data1, # 堆叠在左边第一个上方
color = 'c', label = 'b')
plt.barh(index, data3, a, left = (data1 + data2), # 堆叠在左边第一个和第二个上方
color = 'orange', alpha = 0.5,label = 'c')
plt.legend()