![](/img/trans.png)
[英]I have a bar chart with error bars in matplotlib (python), but i want the error bars in the middle of the bar. how do i do this? Thanks
[英]How do I get all bars in a matplotlib bar chart?
通過調用get_lines()
函數可以輕松檢索折線圖中的所有線條。 我似乎無法找到一個條形圖同等功能,即檢索所有矩形實例在AxesSubplot
。 建議?
如果您想要所有條形,只需捕獲繪圖方法的輸出。 它是一個包含欄的列表:
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')
如果您確實需要坐標區中的所有 Rectangle 對象,但這些對象可能不僅僅是條形,請使用:
bars = [rect for rect in ax.get_children() if isinstance(rect, mpl.patches.Rectangle)]
另一個可能對某些人有用的選項是訪問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)
會給你:
如果您在繪圖中添加一些標簽,您可以構建一個容器字典以通過標簽訪問它們
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")
會給你
當然,您仍然可以訪問容器中的單個條形補丁,例如
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.