负数高于 x 轴的 Matplotlib 条形图 [英] Matplotlib bar chart for negative numbers going above x-axis

查看:45
本文介绍了负数高于 x 轴的 Matplotlib 条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作负值条形图,其中基线 x 轴位于 -10 而不是 0 和值,因为它们都是 -10<x<0,扩展高于基线.

如果我按原样绘制,条形向下延伸:

 将matplotlib.pyplot导入为plt值= [-4,-6,-8,-6,-5]plt.bar(range(len(vals)), vals)

在某种意义上,我可以通过将 10 添加到数据中来伪造它,但随后我必须删除 y-tick 值,我需要保留它们.

new_vals = [val + 10 for val in vals]plt.yticks([])plt.bar(range(len(new_vals)), new_vals)

那么我该如何在第一张图像的y点上制作第二张图像,并且最好在不伪造"任何数据的情况下?

解决方案

跟随

IMO,上述解决方案比

I am trying to make a bar chart of negative values where the baseline x-axis is at -10 instead of 0 and the values, because they are all -10<x<0, extend up from the baseline.

If I plot it as is, the bars extend downward:

import matplotlib.pyplot as plt
vals = [-4, -6, -8, -6, -5]
plt.bar(range(len(vals)), vals)

I could fake it in some sense by adding 10 to the data, but then I would have to remove the y-tick values, and I need to keep them.

new_vals = [val + 10 for val in vals]
plt.yticks([])
plt.bar(range(len(new_vals)), new_vals)

So how can I make the second image with the y-ticks of the first image and, preferably, without "faking" any of the data?

解决方案

Following https://matplotlib.org/gallery/ticks_and_spines/custom_ticker1.html example, you can also do like this:

from matplotlib.ticker import FuncFormatter
def neg_tick(x, pos):
    return '%.1f' % (-x if x else 0) # avoid negative zero (-0.0) labels

formatter = FuncFormatter(neg_tick)
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
plt.bar(range(len(vals)), [-v for v in vals]) # or -numpy.asarray(vals)
# or, let Python enumerate bars:
# plt.bar(*zip(*enumerate(-v for v in vals)))
plt.show()

You cannot not "fake" data. Bar charts plot bars up for positive data and down for negative. If you want things differently, you need to trick bar chart somehow.

IMO, the above solution is better than https://stackoverflow.com/a/11250884/8033585 because it does not need the trick with drawing canvas, changing labels, etc.


If you do want to have "reverted" bar length (as it is in your example), then you can do the following:

from matplotlib.ticker import FuncFormatter
import numpy as np

# shifted up:
vals = np.asarray(vals)
minval = np.amin(vals)
minval += np.sign(minval) # "add" 1 so that "lowest" bar is still drawn
def neg_tick(x, pos):
    return '%.1f' % (x + minval if x != minval else 0)

formatter = FuncFormatter(neg_tick)
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
plt.bar(*zip(*enumerate(-minval + vals)))
plt.show()

这篇关于负数高于 x 轴的 Matplotlib 条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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