为什么我的图表不打印,如何更改条形图颜色?

时间:2018-02-01 07:24:22

标签: python pandas matplotlib

以下是我尝试使用Python 3.6.3打印的数据框。在使用下面的代码更改颜色之前,我的图表打印完美找到。但是,现在图表打印没有任何条形图。

另外,我无法使用下面的列表找出如何更改所有条形图颜色。我在Jupyter的一个项目上工作,图表打印得很好。唯一的问题是仍然没有根据列表调整颜色。只打印出橙色和绿色。

              market_cap_usd  market_cap_perc
id
bitcoin         1.862130e+11        33.481495
ethereum        1.141650e+11        20.527111
ripple          4.906157e+10         8.821376
bitcoin-cash    2.782094e+10         5.002265
cardano         1.522458e+10         2.737413
neo             1.041332e+10         1.872338
stellar         9.829044e+09         1.767283
litecoin        9.758786e+09         1.754651
eos             8.518116e+09         1.531575
nem             7.917498e+09         1.423583

# Colors for the bar plot
COLORS = ['orange', 'green', 'orange', 'cyan', 'cyan', 'blue', 'silver', 'orange', 'red', 'green']

# Plotting market_cap_usd as before but adding the colors and scaling the y-axis  
ax = cap10.plot.bar(color=COLORS, title=TOP_CAP_TITLE, logy=True)

# Annotating the y axis with 'USD'
ax.set_ylabel('USD')

# Final touch! Removing the xlabel as it is not very informative
# ... YOUR CODE FOR TASK 5 ...
ax.set_xlabel('')
plt.show(ax)

1 个答案:

答案 0 :(得分:1)

您可以按自定义颜色修改this solution并设置ylim

COLORS1 = ['orange', 'green', 'orange', 'cyan', 'cyan', 
           'blue', 'silver', 'orange', 'red', 'green']
COLORS2 = [ 'green', 'orange', 'cyan', 'cyan', 'blue', 
            'silver', 'orange', 'red', 'green','orange']

TOP_CAP_TITLE = 'title'

fig = plt.figure() # Create matplotlib figure

ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.

width = 0.4
cap10['market_cap_usd'].plot(kind='bar', title=TOP_CAP_TITLE, color=COLORS1, ax=ax, width=width, position=1, logy=True)
cap10['market_cap_perc'].plot(kind='bar', color=COLORS2, ax=ax2, width=width, position=0)

# Annotating the y axis with 'USD'
ax.set_ylabel('USD')
ax2.set_ylabel('perc')

#set max limit for y of second plot
ax2.set_ylim([0,cap10['market_cap_perc'].max() + 20])

ax.set_xlabel('')
ax2.set_xlabel('')
plt.show()

graph

另一种解决方案是分别绘制每一列:

TOP_CAP_TITLE = 'title'

ax = plt.subplot(211)
ax2 = plt.subplot(212)

cap10['market_cap_usd'].plot(kind='bar',title=TOP_CAP_TITLE, color=COLORS1, ax=ax, logy=True)
cap10['market_cap_perc'].plot(kind='bar', color=COLORS2, ax=ax2)

# Annotating the y axis with 'USD'
ax.set_ylabel('USD')
ax2.set_ylabel('perc')

#if want remove labels of x axis in first plot
ax.set_xticklabels([])
ax.set_xlabel('')
ax2.set_xlabel('')
plt.show()

graph1