【发布时间】:2020-04-23 18:54:24
【问题描述】:
我正在尝试在 Python 中使用 Altair 制作一个条形图,其中条形的宽度取决于源数据框列中的数据。最终目标是得到这样的图表:
条形的高度对应于每种能源技术的边际成本(在源数据框中以列形式给出)。条形宽度对应于每种能源技术的容量(也在源数据框中以列的形式给出)。颜色也是来自源数据框的序数数据。条形按边际成本的升序排序。 (这样的情节在能源行业被称为“发电堆栈”)。这在 matplotlib 中很容易实现,如下面的代码所示:
import matplotlib.pyplot as plt
# Make fake dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
# Choose the width of each bar and their positions
width = [0.1,0.2,3,1.5,0.3]
y_pos = [0,0.3,2,4.5,5.5]
# Make the plot
plt.bar(y_pos, height, width=width)
plt.xticks(y_pos, bars)
plt.show()
(来自https://python-graph-gallery.com/5-control-width-and-space-in-barplots/的代码)
但是有没有办法用 Altair 做到这一点?我想用 Altair 来做这件事,所以我仍然可以获得 Altair 的其他强大功能,比如工具提示、选择器/绑定,因为我有很多其他数据想要在条形图旁边显示。
我的源数据的前 20 行如下所示:
(与上面显示的图表不完全匹配)。
【问题讨论】:
标签: python plot charts bar-chart altair