I am showing images with matplotlib and applying some colormaps to the images. I've figured you can set a default colormap by something like
plt.set_cmap('jet')
and then that colormap will be applied every time when using plt.imshow()
But how about undoing that? If I want to show the original images again without any colormap? I haven't found in the docs anything about that, neither by quick googling so any help would be appreciated.
Thanks!
You can set the colormap using set_cmap as you are aware. This changes the colormap for all subsequent figures plotted. If you want to undo the changes you have made, simply go back to the matplotlib default colormap, which in matplotlib 2 is viridis.
However, there is also a cmap argument for imshow() which lets you change the colormap applied for an individual plot. This means you don't keep having to change the global colormap, however you would have to write this in every call to imshow()
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randn(25).reshape(5,5)
fig, (ax1, ax2) = plt.subplots(1,2)
ax1.imshow(data)
ax1.set_title("Matplotlib default cmap")
ax2.imshow(data, cmap='jet')
ax2.set_title("jet cmap")
plt.show()
Which gives:
The command plt.set_cmap("jet") sets the colormap in the rcParams to be the "jet" colormap.
In order to get back the default colormap, you can set the cmap to the default colormap from the rcParamsDefault dictionary.
import matplotlib.pyplot as plt
print(plt.rcParams["image.cmap"]) # prints viridis
plt.set_cmap("jet")
print(plt.rcParams["image.cmap"]) # prints jet
plt.set_cmap(plt.rcParamsDefault["image.cmap"])
print(plt.rcParams["image.cmap"]) # prints viridis
Related
I played around with colormaps, trying many of them, trying to make my own, both in matplotlib and seaborn.
However now I would like to know which colormap I am using. How can I do that? Is there a command like matplotlib.whichColormap ?
Usually there would be no need to find out the colormap you are using because you define that yourself. I.e. when calling
plt.imshow(..., cmap="viridis")
you already know that you are using "viridis".
If you still feel it would be useful to get that information from an existing ScalarMappable, you may use get_cmap() and it's name attribute:
import matplotlib.pyplot as plt
import numpy as np
a = np.random.rand(4,5)
fig, ax = plt.subplots()
im = ax.imshow(a, cmap="viridis")
cm = im.get_cmap()
print(cm.name) # prints viridis
I am trying to plot data to a figure and respective axis in matplotlib and as new work comes up, recall the figure with the additional plot on the axis:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
x=np.arange(0,20)
y=2*x
fig,ax=plt.subplots()
ax.scatter(x,x)
ax.scatter(x,y)
fig
Which works fine with matplotlib, if I however use seaborn's regplot:
fig2,ax2=plt.subplots()
sns.regplot(x,x,ax=ax2,fit_reg=False)
sns.regplot(x,y,ax=ax2,fit_reg=False)
fig2
fig2 generates the figure that I want but the regplot command generates an empty figure. Is there a way to suppress the regplot's empty output or have it display the updated ax2 without recalling fig2?
It seems you are using the jupyter notebook with the inline backend. In some circumstances regplot triggers the creation of a new figure even if the artists are being added to the previous one and this messes up the output. I don't know why this happens but I found a workaround that might help you, using plt.ioff to temporarily disable automatic display of figures.
plt.ioff()
fig, ax = plt.subplots()
sns.regplot(x, x, ax=ax)
fig
sns.regplot(x, 2 * x, ax=ax)
fig
You have to call plt.ioff before creating the figure for this to work. After that you have to explicitly display the figure. Then you can call plt.ion to restore the default behaviour.
regplot does not generate an empty figure. According to the documentation:
Understanding the difference between regplot() and lmplot() can be a
bit tricky. In fact, they are closely related, as lmplot() uses
regplot() internally and takes most of its parameters. However,
regplot() is an axes-level function, so it draws directly onto an axes
(either the currently active axes or the one provided by the ax
parameter), while lmplot() is a figure-level function and creates its
own figure, which is managed through a FacetGrid.
When I do the following:
fig2,ax2 = plt.subplots()
same_fig2 = sns.regplot(x,x,ax=ax2,fit_reg=False)
same_fig2.figure is fig2
>>> True
I am working on generating some scatter plot with matplotlib.pyplot.scatter() in jupyter notebook, and I found that if I import seaborn package, the scatter plot will lose its color. I am wondering if anyone has a similar issue?
Here is an example code
import matplotlib.pyplot as plt
import seaborn as sb
plt.scatter(range(4),range(4), c=range(4))
The output is
The scatter plot without seaborn is:
That seems to be the way it behaves. In seaborn 0.3 the default color scale was changed to greyscale. If you change your code to:
plt.scatter(range(4),range(4), c=sb.color_palette())
You will get an image with colors similar to your original.
See the Seaborn docs on choosing color palettes for more info.
Another way to fix this is to specify cmap option for plt.scatter() so that it would not be affected by seaborn:
ax = plt.scatter(range(4),range(4), c=range(4), cmap='gist_rainbow')
plt.colorbar(ax)
The result is:
There are many options for cmap here:
http://matplotlib.org/examples/color/colormaps_reference.html
I am using Seaborn to plot some data in Pandas.
I am making some very large plots (factorplots).
To see them, I am using some visualisation facilities at my university.
I am using a Compound screen made up of 4 by 4 monitors with small (but nonzero) bevel -- the gap between the screens.
This gap is black.
To minimise the disconnect between the screen i want the graph backgound to be black.
I have been digging around the documentation and playing around and I can't work it out..
Surely this is simple.
I can get grey background using set_style('darkgrid')
do i need to access the plot in matplotlib directly?
seaborn.set takes an rc argument that accepts a dictionary of valid matplotlib rcparams. So we need to set two things: the axes.facecolor, which is the color of the area where the data are drawn, and the figure.facecolor, which is the everything a part of the figure outside of the axes object.
(edited with advice from #mwaskom)
So if you do:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn
seaborn.set(rc={'axes.facecolor':'cornflowerblue', 'figure.facecolor':'cornflowerblue'})
fig, ax = plt.subplots()
You get:
And that'll work with your FacetGrid as well.
I am not familiar with seaborn but the following appears to let you change
the background by setting the axes background. It can set any of the ax.set_*
elements.
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
m=pd.DataFrame({'x':['1','1','2','2','13','13'],
'y':np.random.randn(6)})
facet = sns.factorplot('x','y',data=m)
facet.set(axis_bgcolor='k')
plt.show()
Another way is to set the theme:
seaborn.set_theme(style='white')
In new versions of seaborn you can also use
axes_style() and set_style() to quickly set the plot style to one of the predefined styles: darkgrid, whitegrid, dark, white, ticks
st = axes_style("whitegrid")
set_style("ticks", {"xtick.major.size": 8, "ytick.major.size": 8})
More info in seaborn docs
I'm editing my graphs step by step. Doing so, plt functions from matplotlib.pyplot apply instantly to my graphical output of pylab. That's great.
If I address axes of a subplot, it does not happen anymore.
Please find both alternatives in my minimal working example.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
f = plt.figure()
sp1 = f.add_subplot(1,1,1)
f.show()
# This works well
sp1.set_xlim([1,5])
# Now I plot the graph
df = pd.Series([0,5,9,10,15])
df.hist(bins=50, color="red", alpha=0.5, normed=True, ax=sp1)
# ... and try to change the ticks of the x-axis
sp1.set_xticks(np.arange(1, 15, 1))
# Unfortunately, it does not result in an instant change
# because my plot has already been drawn.
# If I wanted to use the code above,
# I would have to execute him before drawing the graph.
# Therefore, I have to use this function:
plt.xticks(np.arange(1, 15, 1))
I understand that there is a difference between matplotlib.pyplot and an axis instance. Did I miss anything or does it just work this way?
Most of pyplot functions (if not all) have a call to plt.draw_if_interactive() before returning. So if you do
plt.ion()
plt.plot([1,2,3])
plt.xlim([-1,4])
you obtain that the plot is updated as you go. If you have interactive off, it won't create or update the plot until you don't call plt.show().
But all pyplot functions are wrappers around corresponding (usually) Axes methods.
If you want to use the OO interface, and still draw stuff as you type, you can do something like this
plt.ion() # if you don't have this, you probably don't get anything until you don't call a blocking `plt.show`
fig, ax = plt.subplots() # create an empty plot
ax.plot([1,2,3]) # create the line
plt.draw() # draw it (you can also use `draw_if_interactive`)
ax.set_xlim([-1,4]) #set the limits
plt.draw() # updata the plot
You don't have to use the pyplot you don't want, just remember to draw
The plt.xticks() method calls a function draw_if_interactive() that comes from pylab_setup(), who is updating the graph. In order to do it using sp1.set_xticks(), just call the corresponding show() method:
sp1.figure.show()