如何从多个数据集绘制分组条形图
我正在浏览 Think Stats,我想直观地比较多个数据集。我从书中的示例中可以看到,通过使用书籍作者提供的模块,可以为每个数据集生成具有不同颜色的交错条形图,如何在 pyplot 中获得相同的结果?
I am going through Think Stats and I would like to compare multiple data sets visually. I can see from the book examples that it is possible to generate an interleaved bar graph with a different color for each data set by using a module provided by the book author, how to obtain the same result in pyplot
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
多次调用 bar 函数,每个系列调用一次。您可以使用 left 参数控制条的左侧位置,并且可以使用它来防止重叠。
完全未经测试的代码:
与绘制数据 1 的位置相比,绘制数据 2 的位置向右移动。
Call the bar function multiple times, one for each series. You can control the left position of the bars using the left parameter, and you can use this to prevent overlap.
Entirely untested code:
Data2 will be drawn shifted over the right compared to where data one will be drawn.
Matplotlib 的交错条形图的 示例代码 对于任意实值 x 坐标(如前所述)由@db42)。
但是,如果您的 x 坐标是分类值(例如链接问题中的字典),则从分类值的转换x 坐标到真实 x 坐标是麻烦且不必要的。
您可以使用 matplotlib 的 api 直接并排绘制两个字典。绘制两个相互偏移的条形图的技巧是设置
align=edge
和一个正宽度 (+width
) 来绘制一个条形图,而一个负宽度width (-width
) 用于绘制另一个。为绘制两个字典而修改的示例代码如下所示:
结果:
Matplotlib's example code for interleaved bar charts works nicely for arbitrary real-valued x coordinates (as mentioned by @db42).
However, if your x coordinates are categorical values (like in the case of dictionaries in the linked question), the conversion from categorical x coordinates to real x coordinates is cumbersome and unnecessary.
You can plot two dictionaries side-by-side directly using matplotlib's api. The trick for plotting two bar charts with an offset to each other is to set
align=edge
and a positive width (+width
) for plotting one bar chart, whereas a negative width (-width
) for plotting the other one.The example code modified for plotting two dictionaries looks like the following then:
The result:
我不久前遇到了这个问题,并创建了一个包装函数,它接受一个 2D 数组并自动从中创建一个多条形图:
代码:
如果您对该函数的作用及其背后的逻辑感兴趣,这里有一个(无耻的自我推销)描述它的博客文章的链接。
I came across this problem a while ago and created a wrapper function that takes a 2D array and automatically creates a multi-barchart from it:
The code:
If you're interested in what this function does and the logic behind it, here's a (shamelessly self-promoting) link to the blog post describing it.