I am playing with matplotlib - I have a bar chart, and I want to highlight the bar which user clicks. I have a callback that goes through a rect collection (the one I got from self.axis.bar(...)) and finds out which one was clicked (looking at the coordinates). At this point I want to call something to change the colour of the current bar. Is it possible? How do I do that?
Edited: I guess the answer I am really looking for is if it's possible to make bars to have different colours.
You can set the color of individual bars using the Artist properties. Here's an example:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
bars = ax1.bar(range(1,10), range(1,10), color='blue', edgecolor='black')
bars[6].set_facecolor('red')
plt.show()
Related
this is my first question here and one probably very simple, however I tried to fix any mistake and look more info but with no success, I am new to programming graphs using matplotlib, could anyone help me out? thank you in advance
The goal of the program was to graphic a circle and a label, but label was not appearing:
import matplotlib.pyplot as plt
circle1 = plt.Circle((0, 0), 0.2, color='r',label='Men')
fig, ax = plt.subplots()
ax.add_artist(circle1)
circle1 = plt.Circle((0, 0), 2, color='r',label='Men')
plt.legend(loc='best')
plt.show()
Based on your code, you are only plotting the first circle (with radius 0.2). You never call the second circle, so it does not show up. Not sure what you are going for here. However, BigBen is correct, just use ax.add_patch(circle1) instead and it will show with the labels. With this minor change, your plot will look like this:
You would also want to set x and y axis limits in order to see the entire circle. This code below will allow you to see both circles in full with different labels.
import matplotlib.pyplot as plt
circle1 = plt.Circle((0, 0), 0.2, color='r',label='Small Red',zorder=2)
circle2 = plt.Circle((0, 0), 2, color='b',label='Big Blue',zorder=1)
fig, ax = plt.subplots()
ax.add_patch(circle1)
ax.add_patch(circle2)
plt.legend(loc='best')
ax.set_xlim([-3,3])
ax.set_ylim([-3,3])
plt.show()
And your plot will look like this:
The zorder argument will decide which object shows up in front of the other. They will appear front-to-back in descending order.
import matplotlib
import matplotlib.pyplot as plt
import numpy as nm
x = nm.linspace(start=0,stop=20,num=30)
fig=plt.figure()
ax1 = fig.add_axes([0,0.6,0.6,0.4])
ax2 = fig.add_axes([0,0,0.8,0.4])
ax1.plot(x,nm.sin(x))
ax1.set_xlabel('x',fontsize=15,color='r')
ax1.set_ylabel('sin(x)',fontsize=15,color='r')
ax2.plot(x,nm.cos(x))
ax2.set_xlabel('x',fontsize=15,color='r')
ax2.set_ylabel('cos(x)',fontsize=15,color='r')
plt.show()
The output I am not able to see the xlabel for ax2 and not able to see both y label for ax1 and ax2..The image is present below:
enter code hereenter image description here
This is expected as you are asking to create an axes that is aligned with the left edge of the figure by using fig.add_axes([0,...]). Same thing for the bottom axes, which you have aligned to the bottom-left of the figure using fig.add_axes([0,0,...]).
Increase the first value e.g. fig.add_axes([0.125,...]) to leave room for the axes decorations on the left or bottom of the axes.
It is generally recommended to use the subplots functions (such as add_subplot, plt.subplots or GridSpec) so that these details are handled automatically.
The following creates a plot with a white background thereby ignoring set_facecolor.
import matplotlib.pyplot as plt
from descartes.patch import PolygonPatch
import cartopy.crs as ccrs
fig = plt.figure()
ax = fig.add_subplot(111, projection=ccrs.Mercator())
ax.set_facecolor((198/255, 236/255, 253/255))
plt.show()
If I remove where I set the projection, then the color is as expected. How can I set the background color?
I am plotting my own map using shapely polygons using ax.plot. I wish to set the color of the water by setting the background color since my polygons have holes for representing lakes.
Cartopy's projections create various new properties, including two extra patches, the background and outline patches.
It is likely that the background is the one you want to change, but without further example steps this is not certain. Here is how to set each one:
fig = plt.figure();
ax1 = fig.add_subplot(121, projection=ccrs.Mercator())
ax2 = fig.add_subplot(122, projection=ccrs.Mercator())
ax1.background_patch.set_facecolor((198/255, 236/255, 253/255))
ax2.outline_patch.set_facecolor((198/255., 236/255., 253/255.))
plt.show()
Also take care with your color commands -- the example you gave used integer divide, which results in (0,0,0) = black. On the 2nd suplot you see the color you presumably wanted.
For completeness, note that the regular axis patch is turned off, so changes to that patch will not be seen.
I am using matplotlib in python 2.7. I am trying to create an arrow in the figure area outside of the axes.
from matplotlib.pyplot import *
fig = figure()
ax1 = fig.add_axes([.1,.1,.6,.8])
ax1.annotate('',xy=(.8,.92),xycoords='figure fraction',xytext=(.8,.1)
arrowprops=dict(arrowstyle='->',fc='k',lw=10))
ax2 = fig.add_axes([.85,.1,.1,.8])
ax2.spines['top'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.tick_params(axis='both',which='both',
top='off',right='off',left='off',bottom='off',
labeltop='off',labelright='off',labelleft='off',labelbottom='off')
ax2.patch.set_facecolor('None')
ax2.set_xlim(0,1)
ax2.set_ylim(0,1)
ax2.arrow(.5,0,0,1,fc='k',ec='k',head_width=.25,
head_length=.05,width=.15,length_includes_head=True)
show()
Using
ax1.annotate(...)
gives me a 'blurry' looking arrow. The only way I can figure out how get a better looking arrow is by creating another axes just for adding the arrow and using
ax2.arrow(...)
(the website won't let me post an image, but copy and paste the code and you'll see what I'm talking about)
There's got to be a better way to do this though...
I think changing the arrowstyle will help here. For example, changing it to 'simple' from '->' gives a better looking arrow. You can change the width by playing with the mutation_scale. For example,
ax1.annotate('',xy=(.8,.92),xycoords='figure fraction',xytext=(.8,.1),
arrowprops=dict(arrowstyle="simple",fc="k", ec="k",mutation_scale=30))
Here's your script, with the above simple arrow plotted in blue. Note the difference to the black arrow plotted as a -> arrow with annotate.
from matplotlib.pyplot import *
fig = figure()
ax1 = fig.add_axes([.1,.1,.5,.8])
# Your original arrow (black)
ax1.annotate('',xy=(.7,.92),xycoords='figure fraction',xytext=(.7,.1),
arrowprops=dict(arrowstyle='->',fc='k',lw=10))
# "Simple" arrow (blue)
ax1.annotate('',xy=(.8,.92),xycoords='figure fraction',xytext=(.8,.1),
arrowprops=dict(arrowstyle="simple",fc="b", ec="k",mutation_scale=30))
ax2 = fig.add_axes([.85,.1,.1,.8])
ax2.spines['top'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.tick_params(axis='both',which='both',
top='off',right='off',left='off',bottom='off',
labeltop='off',labelright='off',labelleft='off',labelbottom='off')
ax2.patch.set_facecolor('None')
ax2.set_xlim(0,1)
ax2.set_ylim(0,1)
ax2.arrow(.5,0,0,1,fc='r',ec='k',head_width=.25,
head_length=.05,width=.15,length_includes_head=True)
show()
I've managed to plot a series of points with the following code:
plt = pp.figure()
for i in range(spt.shape[1]):
spktrain = spt[0,i]
for trial in spktrain:
non_z = np.nonzero(trial)
non_z = non_z[0]
pp.plot(t[non_z], trial[non_z], 'bo')
I would like to place alternating bands of white and gray background on the figure in order to separate the data from each iteration of the outer for loop. In other words, I would like the data from each "spktrain" to have it's own background color (the data does not overlap).
How can I go about changing the background color of a figure in a specific region?
You can use axhspan and/or axvspan like this:
import matplotlib.pyplot as plt
plt.figure()
plt.xlim(0, 5)
plt.ylim(0, 5)
for i in range(0, 5):
plt.axhspan(i, i+.2, facecolor='0.2', alpha=0.5)
plt.axvspan(i, i+.5, facecolor='b', alpha=0.5)
plt.show()