挣扎着想出这个。我有一个堆积的条形图,我正在尝试用Python / Matplotlib创建,它似乎覆盖数据而不是堆叠导致不同的颜色(即红色+黄色=橙色而不是堆叠红色和黄色)。谁能看到我做错了什么?
这是我的代码:
#Stacked Bar Char- matplotlib
#Create the general blog and the "subplots" i.e. the bars
f, ax1 = plt.subplots(1, figsize=(10,5))
# Set the bar width
bar_width = 0.75
# positions of the left bar-boundaries
bar_l = [i+1 for i in range(len(df4['bikes']))]
# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(bar_width/2) for i in bar_l]
# Create a bar plot, in position bar_1
ax1.bar(bar_l, df4['bikes1'], width=bar_width, label='bikes', alpha=0.5,color='r', align='center')
# Create a bar plot, in position bar_1
ax1.bar(bar_l, df4['bikes'], width=bar_width,alpha=0.5,color='r', align='center')
# Create a bar plot, in position bar_1
ax1.bar(bar_l, df4['cats1'], width=bar_width, label='cats', alpha=0.5,color='y', align='center')
# Create a bar plot, in position bar_1
ax1.bar(bar_l, df4['cats'], width=bar_width,alpha=0.5,color='y', align='center')
# set the x ticks with names
plt.xticks(tick_pos, df4['Year'])
# Set the label and legends
ax1.set_ylabel("Count")
ax1.set_xlabel("Year")
plt.legend(loc='upper left')
ax1.axhline(y=0, color='k')
ax1.axvline(x=0, color='k')
# Set a buffer around the edge
plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width])
plt.show()
答案 0 :(得分:0)
您必须手动计算 cats 栏开始的位置(当 cats 正在绘制时,查看代码中的bottom
变量)。您必须根据数据框中的数据提出自己的方法来计算 cats 条的位置。
你的颜色混淆了,因为你使用alpha
变量,当条形重叠时,颜色会混淆:
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
df4 = pd.DataFrame.from_dict({'bikes1':[-1,-2,-3,-4,-5,-3], 'bikes':[10,20,30,15,11,11],
'cats':[1,2,3,4,5,6], 'cats1':[-6,-5,-4,-3,-2,-1], 'Year': [2012,2013,2014,2015,2016,2017]})
#Create the general blog and the "subplots" i.e. the bars
f, ax1 = plt.subplots(1, figsize=(10,5))
# Set the bar width
bar_width = 0.75
# positions of the left bar-boundaries
bar_l = [i+1 for i in range(len(df4['bikes']))]
# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(bar_width/2) for i in bar_l]
# Create a bar plot, in position bar_1
ax1.bar(bar_l, df4['bikes1'], width=bar_width, label='bikes', alpha=0.5,color='r', align='center')
# Create a bar plot, in position bar_1
ax1.bar(bar_l, df4['bikes'], width=bar_width,alpha=0.5,color='r', align='center')
# Create a bar plot, in position bar_1
ax1.bar(bar_l, df4['cats1'], width=bar_width, label='cats', alpha=0.5,color='y', align='center',
bottom=[min(i,j) for i,j in zip(df4['bikes'],df4['bikes1'])])
# Create a bar plot, in position bar_1
ax1.bar(bar_l, df4['cats'], width=bar_width,alpha=0.5,color='y', align='center',
bottom=[max(i,j) for i,j in zip(df4['bikes'],df4['bikes1'])])
# set the x ticks with names
plt.xticks(tick_pos, df4['Year'])
# Set the label and legends
ax1.set_ylabel("Count")
ax1.set_xlabel("Year")
plt.legend(loc='upper left')
ax1.axhline(y=0, color='k')
ax1.axvline(x=0, color='k')
# Set a buffer around the edge
plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width])
plt.show()