用颜色图图例绘制条形图 [英] Plotting bar charts with a colormap legend

查看:139
本文介绍了用颜色图图例绘制条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

 将matplotlib.pyplot导入为plt从matplotlib导入cm将numpy导入为npy = np.array([1,4,3,2,7,11])颜色= cm.hsv(y/float(max(y)))情节= plt.scatter(y,y,c = y,cmap ='hsv')plt.clf()plt.colorbar(图)plt.bar(范围(len(y)),y,颜色=颜色)plt.show() 

我想对图例进行颜色映射,使其出现在图表的右上角(当然要小得多).由于色彩图与实际的条形有些冲突,此刻我的图像看起来有些笨拙.

谢谢.

解决方案

Consider the following:

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

y = np.array([1, 4, 3, 2, 7, 11])
colors = cm.hsv(y / float(max(y)))
plot = plt.scatter(y, y, c = y, cmap = 'hsv')
plt.clf()
plt.colorbar(plot)
plt.bar(range(len(y)), y, color = colors)
plt.show()

I want to colormap legend to appear on the top right of the graph (much smaller of course). My image at the moment looks rather clunky as the colormap is clashing somewhat with the actual bars.

Thanks.

解决方案

Following this answer:

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

y = np.array([1, 4, 3, 2, 7, 11])
colors = cm.hsv(y / float(max(y)))

fig, ax = plt.subplots()
plot = ax.scatter(y, y, c = y, cmap = 'hsv')
plt.cla()
ax.bar(range(len(y)), y, color = colors)

cbaxes = inset_axes(ax, width="30%", height="3%", loc=2)
plt.colorbar(plot, cax=cbaxes, orientation='horizontal', ticks=[0,2,4,6,8,10])

I use plt.subplots to easily reference the Axes (ax). You can move the color bar and change its size by editing the last 2 lines (for instance changing loc can set which corner you want the colorbar to be in).

这篇关于用颜色图图例绘制条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆