Matplotlib:从条形图中获取颜色和 x/y 数据
Matplotlib: get colors and x/y data from a bar plot
我有一个条形图,我想获取它的颜色和 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()
是否有任何方法 like ax.get_xvalues()
, ax.get_yvalues()
, ax.get_colors()
,我可以使用它们以便从 ax
列表 x_values
、y_values_1
、y_values_2
以及颜色 'r'
和 'b'
?
ax
知道它在绘制什么几何对象,但是 什么都没有 它会跟踪添加这些几何对象的时间,当然它不知道他们是什么 "mean":哪个补丁来自哪个条形图,等等。编码人员需要跟踪它以重新提取正确的部分以供进一步使用。很多Python程序常用的方法是:调用barplot
returns a 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)
对上述答案稍作改动,将其全部放在对另一个绘图命令的调用中:
# 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() )
换句话说,我似乎需要在轴句柄和容器句柄之间有一个轴属性,以使其更通用一些。
我有一个条形图,我想获取它的颜色和 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()
是否有任何方法 like ax.get_xvalues()
, ax.get_yvalues()
, ax.get_colors()
,我可以使用它们以便从 ax
列表 x_values
、y_values_1
、y_values_2
以及颜色 'r'
和 'b'
?
ax
知道它在绘制什么几何对象,但是 什么都没有 它会跟踪添加这些几何对象的时间,当然它不知道他们是什么 "mean":哪个补丁来自哪个条形图,等等。编码人员需要跟踪它以重新提取正确的部分以供进一步使用。很多Python程序常用的方法是:调用barplot
returns a 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)
对上述答案稍作改动,将其全部放在对另一个绘图命令的调用中:
# 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() )
换句话说,我似乎需要在轴句柄和容器句柄之间有一个轴属性,以使其更通用一些。