pyplot/matplotlib条形图,其填充颜色取决于值 [英] pyplot/matplotlib Bar chart with fill color depending on value

查看:46
本文介绍了pyplot/matplotlib条形图,其填充颜色取决于值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 matplotlib/pyplot 制作 python

I want to produce in python with matplotlib/pyplot

  • 根据值填充的条形图.
  • 图例颜色栏

同时将模块依赖保持在最低限度.

while keeping module dependencies at a minimum.


有没有比这更简单的东西了?

Is there something simpler than:

import matplotlib.pyplot as plt

def color_gradient ( val, beg_rgb, end_rgb, val_min = 0, val_max = 1):
    val_scale = (1.0 * val - val_min) / (val_max - val_min)
    return ( beg_rgb[0] + val_scale * (end_rgb[0] - beg_rgb[0]),
             beg_rgb[1] + val_scale * (end_rgb[1] - beg_rgb[1]),
             beg_rgb[2] + val_scale * (end_rgb[2] - beg_rgb[2]))

# -----------------------------------------------
x_lbls = [ "09:00", "09:15", "10:10"]
y_vals = [       7,       9,       5]

plt_idx = np.arange( len( x_lbls))
bar_wd  = 0.35

grad_beg, grad_end = ( 0.5, 0.5, 0.5), (1, 1, 0)
col_list = [ color_gradient( val,
                             grad_beg,
                             grad_end,
                             min( y_vals),
                             max( y_vals)) for val in y_vals]

plt.bar( plt_idx, y_vals, color = col_list)
plt.xticks( plt_idx + bar_wd, x_lbls)
plt.show()

这仍然缺少图例颜色栏


我在 R 中使用 ggplot 的解决方案是:

my solution in R with ggplot would be:

library(ggplot2)
df = data.frame( time = 1:10, vals = abs(rnorm( n = 10)))
ggplot( df, aes( x = time, y = vals, fill = vals)) + 
  geom_bar(stat = "identity") + 
  scale_fill_gradient(low="#888888",high="#FFFF00")

并产生所需的输出:

推荐答案

我不知道如何在不绘制其他内容然后清除它的情况下让颜色栏工作,因此这不是最优雅的解决方案.

I couldn't figure out how to get the colorbar to work without plotting something else and then clearing it, so it's not the most elegant solution.

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()

这篇关于pyplot/matplotlib条形图,其填充颜色取决于值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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