如何在matplotlib条形图中获得所有条形图?

时间:2014-03-27 13:19:23

标签: python matplotlib

通过调用get_lines()函数可以轻松检索折线图中的所有行。我似乎找不到条形图的等效函数,即检索AxesSubplot中的所有Rectangle实例。建议?

2 个答案:

答案 0 :(得分:13)

如果你想要所有的条形图,只需从绘图方法中捕获输出。它是一个包含条形的列表:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.arange(5)
y = np.random.rand(5)

bars = ax.bar(x, y, color='grey')    
bars[3].set_color('g')

enter image description here

如果您确实想要轴中的所有Rectangle对象,但这些可以更多只是条形,请使用:

bars = [rect for rect in ax.get_children() if isinstance(rect, mpl.patches.Rectangle)]

答案 1 :(得分:0)

另一个可能对某些人有用的选项是访问 ax.containers。你必须小心一点,因为如果你的情节包含其他类型的容器,你也会得到它们。只获取酒吧容器之类的东西

from matplotlib.container import BarContainer
bars = [i for i in ax.containers if isinstance(i, BarContainer)]

这可以通过一些技巧变得非常强大(从公认的例子中汲取灵感)。

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.arange(5)
y = np.random.rand(2, 5)

ax.bar(x, y[0], width=0.5)
ax.bar(x + 0.5, y[1], width=0.5)

for bar, color in zip(ax.containers, ("red", "green")):
    # plt.setp sets a property on all elements of the container
    plt.setp(bar, color=color)

会给你:

enter image description here

如果你在你的图中添加一些标签,你可以构建一个容器字典来通过标签访问它们

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.arange(5)
y = np.random.rand(2, 5)

ax.bar(x, y[0], width=0.5)
ax.bar(x + 0.5, y[1], width=0.5, label='my bars')

named_bars = {i.get_label(): i for i in ax.containers}
plt.setp(named_bars["my bars"], color="magenta")

会给你

enter image description here

当然,您仍然可以访问容器中的单个条形补丁,例如

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.arange(5)
y = np.random.rand(2, 5)

ax.bar(x, y[0], width=0.5)
ax.bar(x + 0.5, y[1], width=0.5)

plt.setp(ax.containers[0], color="black")
plt.setp(ax.containers[1], color="grey")
ax.containers[0][3].set_color("red")

enter image description here