I have a bar plot and I want to get its colors and x/y values. Here is a sample code:
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()
Are there any methods like ax.get_xvalues(), ax.get_yvalues(), ax.get_colors(), which I can use so I could extract back from ax the lists x_values, y_values_1, y_values_2 and the colors 'r' and 'b'?
The ax knows what geometric objects it's drawing, but nothing about it keeps track of when those geometric objects were added, and of course it doesn't know what they "mean": which patch comes from which bar-plot, etc. The coder needs to keep track of that to re-extract the right parts for further use. The way to do this is common to many Python programs: the call to barplot returns a BarContainer, which you can name at the time and use later:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With