我想尝试使用以下代码创建位置明智的堆积条形图
example of data
values are based on different different altitude on particular location
location N T S Su
1 25 20 30 40
:
:
N
代码:=
import numpy as np
import matplotlib.pyplot as plt
N=np.array([20, 35, 30, 35, 27])
T=np.array([25, 32, 34, 20, 25])
S=np.array([30,5,35,10,20])
Su=np.array([30,5,35,10,20])
No =len(N)
ind = np.arange(No) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, N, width, color='r')
p2 = plt.bar(ind, T, width, color='y',bottom=N)
p3=plt.bar(ind,S,width,color='g',bottom=N+T)
p4=plt.bar(ind,Su,width,color='w',bottom=N+T+S)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind+width/2., ('G1', 'G2', 'G3', 'G4', 'G5') )
plt.yticks(np.arange(0,200,10))
plt.legend( (p1[0], p2[0],p3[0],p4[0]),
('Normal','Trapping','Super','Sub') )
plt.show()
它仅适用于T,N,S,Su的单个值 但是特定纬度的某些时间,T,N,Su,S的长值会重复,应该在堆栈栏中调整但我无法做到请帮帮我 T,N,S,Su的值分别基于单个堆栈条或所有
分组具有相同的颜色example location T N S Su N T S N
1 25 30 35 40 45 50 55 60
:
:
N
在这个例子中N,S对不同海拔高度的单个位置有多个值同样有N个位置并且有相似的条件请帮我解决
答案 0 :(得分:2)
您可以使用pandas
模块:
import pandas as pd
df = pd.DataFrame({'Location':['G1', 'G2', 'G3', 'G4', 'G5'],
'Normal':np.array([20, 35, 30, 35, 27]),
'Trapping':np.array([25, 32, 34, 20, 25]),
'Super':np.array([30,5,35,10,20]),
'Sub':np.array([30,5,35,10,20])})
df.plot(kind='bar', x='Location', stacked=True)
df2 = pd.concat([df, df[['Normal', 'Sub', 'Super']]], axis=1)
df2 = df2.groupby(level=0, axis=1).sum()
df2.plot(kind='bar', x='Location', stacked=True)
对于你的例子,这会产生:
如果我们复制一些列pd.concat([df, df[['Normal', 'Sub', 'Super']]], axis=1)
来制作:
Location Normal Sub Super Trapping Normal Sub Super
0 G1 20 30 30 25 20 30 30
1 G2 35 5 5 32 35 5 5
2 G3 30 35 35 34 30 35 35
3 G4 35 10 10 20 35 10 10
4 G5 27 20 20 25 27 20 20
然后你可以分组并求和,然后重新绘制: