Especially when working with grayscale images it is tedious to set the color map for every imshow command as imshow(i, cmap='gray'). How can I set the default color map matplotlib uses to grayscale or any other colormap?
To change the default colormap only for the current interactive session or one script use
import matplotlib as mpl
mpl.rc('image', cmap='gray')
For versions of matplotlib prior to 2.0 you have to use the rcParams dict. This still works in newer versions.
import matplotlib.pyplot as plt
plt.rcParams['image.cmap'] = 'gray'
To change the default colormap permanently edit the matplotlibrc configuration file and add the line image.cmap: gray.
Replace the value gray with any other valid colormap according to your needs.
The config file should be at ~/.config/matplotlib/matplotlibrc, but you can find out the exact location with
mpl.matplotlib_fname()
This is especially useful if you have multiple matplotlib versions in different virtual environments.
See also http://txt.arboreus.com/2014/10/21/how-to-set-default-colormap-in-matplotlib.html
and for general configuration of Matplotlib http://matplotlib.org/users/customizing.html
You can do either,
plt.set_cmap('jet')
or
plt.rcParams['image.cmap']='jet'
However note that if you are passing value for color parameter in any of the APIs then this default will be ignored. In that case you should do something like this:
color = plt.cm.hsv(r) # r is 0 to 1 inclusive
line = matplotlib.lines.Line2D(xdata, ydata, color=color)
Related
I've set my plot to transparent so when i access it after plotting,axis and labels looks dark
How can i set the label's and axis to "white" .??
I've tried this
import seaborn as sns
DATA=sns.load_dataset("tips")
import matplotlib.pyplot as plt
plt.figure()
sns.set_style(style="white")
ax=sns.clustermap(DATA.corr(),
cmap="viridis")
#ax.xaxis.label.set_color('white')
#ax.yaxis.label.set_color('white')
plt.savefig("clustermap",transparent=True)
Note that i don't want to change the ' background ' color, just the label and axis color
You can probably use the seaborn.set() function. Here you have a previous answer:
Setting plot background colour in Seaborn
Here you have an example it seems to work in your case (at least in my environment ;-) ):
sns.set(rc={'axes.facecolor':'white', 'figure.facecolor':'white'})
to change just the axis's labels you can use this:
sns.set(rc{'ytick.labelcolor':'white','xtick.labelcolor':'white'})
There are a lot of very fine parameters to set your plot. You can review the full list of parameters just with the command:
plt.rcParams
You can get many details on such command in the link I gave before, going to the Joelostblom answer
From what I understand of this documentation matplotlib provides 3 ways to change the style parameters for plotting (things like axes.grid). Those ways are: using style sheets to set many parameters at a time; setting specific parameters through matplotlib.rcParams or matplotlib.rc; or using a matplotlibrc file to set defaults.
I would like to understand if all of the parameters are accessible in each of the methods I listed above and where I can find a comprehensive list of all of the parameters.
I have tried to understand this from the linked documentation, but I often fail. A specific example is setting the axis font. I typically use a combination like this:
axis_font = {'fontname':'Arial', 'size':'32'}
ax.set_ylabel('some axis title',**axis_font)
But it is not clear what matplotlib parameter (if any) I have set. Does there exist a parameter for the axis font that could be included in a style file for example?
Other attempts in my code include confusing blocks like:
legend_font = {'fontname':'Arial', 'size':'22'}
#fonts global settings
matplotlib.rc('font',family=legend_font['fontname'])
By the names it seems like it would be changing the legend font, but actually it is clearly setting the parameter for the overall font. And the size is not being used. Are there matplotlib parameters for specifically the legend font and legend size?
The things I've tried are:
Checking the example matplotlibrc at the bottom of the linked page (no sign of axis or legend fonts specifically)
Printing matplotlib.rcParams (no sign of axis or legend fonts)
Checking the axis api (could not match up with example style files e.g. the classic predefined style file has facecolor set, which is mentioned in that page, but it also has edgecolor set which is not mentioned on the page)
The rcParams property which changes the font is font.family it accepts 'serif', 'sans-serif', 'cursive', 'fantasy', and 'monospace' as outlined in the linked sample matplotlibrc file. If text.usetex is False it also accepts any concrete font name or list of font names - which will be tried in the order they are specified until one works.
This method applies the specified font name to the entire figure (and to all figures when done globally). If you want to modify the font family for an individual Text instance (i.e. an axis label) you can use matplotlib.text.Text.set_family() (which is an alias for matplotlib.text.Text.set_fontfamily())
import matplotlib.pyplot as plt
ylabel = plt.ylabel("Y Label")
ylabel.set_family("DejaVu Serif")
plt.xlabel("X Label")
plt.show()
And to set the font family for just a legend instance you can use plt.setp, e.g.
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
ylabel = plt.ylabel("Y Label")
plt.xlabel("X Label")
ylabel.set_family("DejaVu Serif")
legend = plt.legend(handles = [mpatches.Patch(color='grey', label="Label")])
plt.setp(legend.texts, family="EB Garamond")
plt.show()
Note that this method will not work when text.usetex is True.
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
In regular matplotlib you can specify various marker styles for plots. However, if I import seaborn, '+' and 'x' styles stop working and cause the plots not to show - others marker types e.g. 'o', 'v', and '*' work.
Simple example:
import matplotlib.pyplot as plt
import seaborn as sns
x_cross = [768]
y_cross = [1.028e8]
plt.plot(x_cross, y_cross, 'ok')
plt.gca().set_xlim([10, 1e4])
plt.gca().set_ylim([1, 1e18])
plt.xscale('log')
plt.yscale('log')
plt.show()
Produces this: Simple Seaborn Plot
Changing 'ok' on line 6 to '+k' however, no longer shows the plotted point. If I don't import seaborn it works as it should: Regular Plot With Cross Marker
Could someone please enlighten me as to how I change the marker style to a cross type when seaborn being used?
The reason for this behaviour is that seaborn sets the marker edge width to zero. (see source).
As is pointed out in the seaborn known issues
An unfortunate consequence of how the matplotlib marker styles work is that line-art markers (e.g. "+") or markers with facecolor set to "none" will be invisible when the default seaborn style is in effect. This can be changed by using a different markeredgewidth (aliased to mew) either in the function call or globally in the rcParams.
This issue is telling us about it as well as this one.
In this case, the solution is to set the markeredgewidth to something larger than zero,
using rcParams (after importing seaborn):
plt.rcParams["lines.markeredgewidth"] = 1
using the markeredgewidth or mew keyword argument
plt.plot(..., mew=1)
However, as #mwaskom points out in the comments, there is actually more to it. In this issue it is argued that markers should be divided into two classes, bulk style markers and line art markers. This has been partially accomplished in matplotlib version 2.0 where you can obtain a "plus" as marker, using marker="P" and this marker will be visible even with markeredgewidth=0.
plt.plot(x_cross, y_cross, 'kP')
It is very like to be a bug. However you can set marker edge line width by mew keyword to get what you want:
import matplotlib.pyplot as plt
import seaborn as sns
x_cross = [768]
y_cross = [1.028e8]
# set marker edge line width to 0.5
plt.plot(x_cross, y_cross, '+k', mew=.5)
plt.gca().set_xlim([10, 1e4])
plt.gca().set_ylim([1, 1e18])
plt.xscale('log')
plt.yscale('log')
plt.show()
For some reason this code creates a figure that is only the standard size: it doesn't change the height or width (I chose widths and heights that are ludicrous to clearly illustrate the problem):
import matplotlib.pyplot as plt
fig = plt.figure()
fig.set_figwidth(30)
fig.set_figheight(1)
print('Width: {}'.format(fig.get_figwidth()))
plt.show()
I'm running on OSX 10.10.4, Python 3.4.3, Matplotlib 1.4.3. (Installed via Macports.) Any ideas? What am I missing?
The optional parameter forward propagates changes to the canvas in a GUI window that already exists.
Documentation here:
optional kwarg forward=True will cause the canvas size to be automatically updated; e.g., you can resize the figure window from the shell
Using Figure(figsize=(w,h)) also works.
For Matplotlib 2.2.0 and newer
forward=True is the default for all three of set_figheight, set_figwidth, and set_size_inches (set_size_inches changes both height and width simultaneously).
For Matplotlib 1.5.0
forward=True must be specified explicitly as it is False by default. (In Matplotlib 2.0.0, the default is changed to True only for set_size_inches).
For Matplotlib 1.4.3 and older
forward is only supported by set_size_inches.
set_figheight and set_figwidth do not support this argument, so it is a bit difficult to only change a single dimension of a pre-created GUI.
I'm not certain why those documented functions don't work, but they have been fixed for the next matplotlib release (>v1.4.3). As a workaround until the next release, replacing set_figwidth and set_figheight solves this problem.
import matplotlib.pyplot as plt
fig = plt.figure()
# Instead of set_figwidth(30)
fig.set_size_inches(30, fig.get_figheight(), forward=True)
plt.show()