如何制作专栏' A_up'列上的堆栈' B_down'专栏' C_up'列上的堆栈' D_down'

时间:2017-04-27 14:41:29

标签: python pandas matplotlib plot

enter image description here

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({
    'A_up':np.array([200,316,440,560,664,765,859,944],dtype='int32'),
    'B_down':np.array([258,443,590,713,822,921,1015,1100],dtype='int32'),
    'C_up':np.array([240,356,540,590,674,795,899,984],dtype='int32'),
    'D_down':np.array([258,443,590,713,822,921,1015,1100],dtype='int32'),
},index=pd.Series(['10000','20000','30000','40000','50000','60000','70000','80000']))

df.plot.bar()
plt.show()

如何制作专栏' A_up'列上的堆栈' B_down'专栏' C_up'列上的堆栈' D_down'?

1 个答案:

答案 0 :(得分:2)

也许是这样的,凯人。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({
    'A_up':np.array([200,316,440,560,664,765,859,944],dtype='int32'),
    'B_down':np.array([258,443,590,713,822,921,1015,1100],dtype='int32'),
    'C_up':np.array([240,356,540,590,674,795,899,984],dtype='int32'),
    'D_down':np.array([258,443,590,713,822,921,1015,1100],dtype='int32'),
},index=pd.Series(['10000','20000','30000','40000','50000','60000','70000','80000']))


N = df.shape[0]
ind = np.arange(N)
width = .3

p1 = plt.bar(ind-width/2,df['B_down'], color='red', width=width)
p2 = plt.bar(ind-width/2,df['A_up'], color='blue', width=width)

p3 = plt.bar(ind+width/2,df['D_down'], color='orange', width=width)
p4 = plt.bar(ind+width/2,df['C_up'], color='maroon', width=width)
plt.xticks(ind,df.index)
plt.legend([p1,p2,p3,p4], ['B_down','A_up','D_down','C_up'])

plt.show()

enter image description here

或许这个:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({
    'A_up':np.array([200,316,440,560,664,765,859,944],dtype='int32'),
    'B_down':np.array([258,443,590,713,822,921,1015,1100],dtype='int32'),
    'C_up':np.array([240,356,540,590,674,795,899,984],dtype='int32'),
    'D_down':np.array([258,443,590,713,822,921,1015,1100],dtype='int32'),
},index=pd.Series(['10000','20000','30000','40000','50000','60000','70000','80000']))
​
​
N = df.shape[0]
ind = np.arange(N)
width = .3
​
p1 = plt.bar(ind-width/2,df['B_down'], color='red', width=width)
p2 = plt.bar(ind-width/2,df['A_up'], color='blue', width=width, bottom=df['B_down'])
​
p3 = plt.bar(ind+width/2,df['D_down'], color='orange', width=width)
p4 = plt.bar(ind+width/2,df['C_up'], color='maroon', width=width, bottom=df['D_down'])
plt.xticks(ind,df.index)
plt.legend([p1,p2,p3,p4], ['B_down','A_up','D_down','C_up'])
​
plt.show()

enter image description here