【问题标题】:Matplotlib: get colors and x/y data from a bar plotMatplotlib:从条形图中获取颜色和 x/y 数据
【发布时间】:2015-10-12 14:30:29
【问题描述】:

我有一个条形图,我想获取它的颜色和 x/y 值。这是一个示例代码:

import matplotlib.pyplot as plt
def main():
    x_values = [1,2,3,4,5]
    y_values_1 = [1,2,3,4,5]
    y_values_2 = [2,4,6,8,10]
    f, ax = plt.subplots(1,1)
    ax.bar(x_values,y_values_2,color='r')
    ax.bar(x_values,y_values_1,color='b')
    #Any methods?
    plt.show()
if __name__ == '__main__':
    main()

是否有任何方法 ax.get_xvalues()ax.get_yvalues()ax.get_colors(),我可以使用这些方法,以便从ax 列表中提取x_valuesy_values_1y_values_2 和颜色 'r''b'?

【问题讨论】:

  • Sooorrrrt of 但它们会很脆弱且不方便。通常,您会通过例如rbar = ax.bar(x_values,y_values_2,color='r') 保留计算出的条形图值,然后使用rbar。你能做到吗?
  • 我不喜欢。但我会满足于你得到的任何东西:)

标签: python matplotlib colors bar-chart


【解决方案1】:

ax 知道它正在绘制哪些几何对象,但没有跟踪这些几何对象的添加时间,当然它也不知道它们“意味着”什么:补丁来自哪个条形图等。编码人员需要跟踪它以重新提取正确的部分以供进一步使用。执行此操作的方法对许多 Python 程序很常见:调用 barplot 返回一个 BarContainer,您可以当时命名并稍后使用:

import matplotlib.pyplot as plt
def main():
    x_values = [1,2,3,4,5]
    y_values_1 = [1,2,3,4,5]
    y_values_2 = [2,4,6,8,10]
    f, ax = plt.subplots(1,1)
    rbar = ax.bar(x_values,y_values_2,color='r')
    bbar = ax.bar(x_values,y_values_1,color='b')
    return rbar, bbar

if __name__ == '__main__':
    rbar, bbar = main()
    # do stuff with the barplot data:
    assert(rbar.patches[0].get_facecolor()==(1.0,0.,0.,1.)) 
    assert(rbar.patches[0].get_height()==2)

【讨论】:

  • 我仍然希望得到一个不使用rbarbbar 并直接从ax 本身提取数据的答案。但是,这也是一个有用的答案。谢谢!
  • @noam 从 ax 获取,您可以执行以下操作:axis = plot.gca() bar_container = axis.containers[0] print(bar_container.patches[0].get_facecolor())
【解决方案2】:

与上述答案略有不同,将其全部放在对另一个绘图命令的调用中:

# plot various patch objects to ax2
ax2 = plt.subplot(1,4,2)
ax2.hist(...)
# start a new plot with same colors as i'th patch object
ax3 = plt.subplot(1,4,3)
plot(...,...,color=ax2.axes.containers[i].patches[0].get_facecolor() )

换句话说,我似乎需要在轴句柄和容器句柄之间添加一个轴属性,以使其更通用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2020-12-03
    • 2011-07-12
    • 2018-09-07
    • 1970-01-01
    • 2022-01-14
    • 2019-06-11
    相关资源
    最近更新 更多