如何仅显示条形图的轮廓matplotlib [英] How to show only the outline of a bar plot matplotlib

查看:81
本文介绍了如何仅显示条形图的轮廓matplotlib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ma​​tplotlib 中将数据绘制为条形图,并试图只显示条形的轮廓,以便它显示为数据的阶梯图".

I'm plotting data as a bar plot in matplotlib and am trying to only show the outline of the bars, so that it appears as a 'stepped graph' of the data.

我在下面添加了我的代码以及所需输出的图像.

I've added my code below along with an image of the desired output.

plt.bar(x, y, align='center', width=0.1, edgecolor='black', color='none')

是否有其他库可以生成此内容? bar 关键字参数似乎没有什么可以实现的.

Are there any other libraries that may be able to produce this? The bar keyword arguments don't seem to have anything that can.

推荐答案

您的图像看起来像一个围绕每个 x,y 值的水平函数.以下代码对此进行了模拟:

Your image looks like a function that is horizontal around each x,y value. The following code simulates this:

  • 对于每个 x,y:创建两个新点,一个位于 x-0.5,一个位于 x+0.5,两者都具有相同的 y
  • 要在末端闭合形状,请在开头添加 (x[0]-0.5, 0),在末尾添加 (x[-1]+0.5, 0).
import numpy as np
from matplotlib import pyplot as plt

x = np.arange(0, 30, 1)
y = np.random.uniform(2, 10, 30)
xs = [x[0] - 0.5]
ys = [0]
for i in range(len(x)):
    xs.append(x[i] - 0.5)
    xs.append(x[i] + 0.5)
    ys.append(y[i])
    ys.append(y[i])
xs.append(x[-1] + 0.5)
ys.append(0)
plt.plot(xs, ys, color='dodgerblue')
# optionally color the area below the curve
plt.fill_between(xs, 0, ys, color='gold')

PS:@AsishM.在评论中提到 matplotlib 也有自己的 step 函数.如果该功能实现,请使用该功能.如果您需要一些额外的控制或变化,这个答案可以作为一个开始,例如为曲线下方的区域着色或处理末端的形状.

PS: @AsishM. mentioned in the comments that matplotlib also has its own step function. If that function fulfils, please use that one. If you need some extra control or variation, this answer could give a start, such as coloring the area below the curve or handling the shape at the ends.

这篇关于如何仅显示条形图的轮廓matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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