Is it possible to change what colors Matplotlib cycles through when it is generating its own colors for a graph's lines? I'm using the pylab module.
from pylab import *
import matplotlib.cm as cm
x=[1,2,3,4]
y=[5,6,7,8]
fig1 = Figure()
plot1 = fig1.add_subplot(311)
plot1.plot(x,y)
plot2 = fig1.add_subplot(312)
plot2.plot(x,y)
plot3 = fig1.add_subplot(313)
plot3.plot(x,y)
Yes, of course. Since it accept many kinds of color definition. It's easy to define your own color map. Here I just get colors from the colormap hot
import pylab as py
import numpy as np
import matplotlib.cm as cm
a = np.arange(0,10)
py.figure()
for i in np.arange(10):
c = cm.hot(i/10.,1)
py.plot(a,i*a,color=c)
py.show()
The colors are extracted from color maps. You can use one of the predefined colormaps, or define your own.
Unfortunately there is no way to use multiple colormaps per figure, you have to do it manually:
import pylab as pl
import matplotlib.cm as cm
xval = pl.arange(0, 20, 0.2)
pl.subplot(311)
pl.plot(xval, pl.sin(xval), c=cm.summer(0))
pl.subplot(312)
pl.plot(xval, pl.cos(xval), c=cm.spring(0))
pl.subplot(313)
pl.plot(xval, pl.arctan(xval), xval, pl.fabs(xval))
pl.show()
Related
How can I set a default set of colors for plots made with matplotlib? I can set a particular color map like this
import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure(i)
ax=plt.gca()
colormap = plt.get_cmap('jet')
ax.set_color_cycle([colormap(k) for k in np.linspace(0, 1, 10)])
but is there some way to set the same set of colors for all plots, including subplots?
Sure! Either specify axes.color_cycle in your .matplotlibrc file or set it at runtime using matplotlib.rcParams or matplotlib.rc.
As an example of the latter:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Set the default color cycle
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "k", "c"])
x = np.linspace(0, 20, 100)
fig, axes = plt.subplots(nrows=2)
for i in range(10):
axes[0].plot(x, i * (x - 10)**2)
for i in range(10):
axes[1].plot(x, i * np.cos(x))
plt.show()
Starting from matplotlib 1.5, mpl.rcParams['axes.color_cycle'] is deprecated. You should use axes.prop_cycle:
import matplotlib as mpl
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "#e94cdc", "0.7"])
In the version of 2.1.0, the below works for me, using set_prop_cycle and module cycler
from cycler import cycler
custom_cycler = (cycler(color=['r','b','m','g']))
ax.set_prop_cycle(custom_cycler)
you can add additional line attribute
custom_cycler = (cycler(color=['r','b','m','g']) + cycler(lw=[1,1,1,2]))
'ax' comes from ax=plt.axes() or any axes generator
I'm using inset_axes() to control the placement of my colorbar legend. The label hangs off the plot just a little bit. Is there a way to just nudge it over without having to do bbox_to_anchor()? Some way to do an offset from the loc parameter? I do want to keep it in the lower left.
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
set1 = ax2.scatter(df.x, df.y,
edgecolors = 'none',
c = df.recommended_net_preferred_for_analysis_meters,
norm = mcolors.LogNorm(), cmap='jet')
cbaxes = inset_axes(ax2, width="30%", height="3%", loc=3)
plt.colorbar(set1, cax=cbaxes, format = '%1.2f', orientation='horizontal')
cbaxes.xaxis.set_ticks_position("top")
I am trying to export a pcolor figure with a colorbar.
The cmap of the colorbar has a transparent color.
The exported figure has transparent colors in the axes but not in the colorbar. How can I fix this?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
x = np.random.random((10, 10))
colors = [(0,0,0,0), (0,0,0,1)]
cm = LinearSegmentedColormap.from_list('custom', colors, N=256, gamma=0)
plt.pcolor(x,cmap=cm)
plt.colorbar()
plt.savefig('figure.pdf',transparent=True)
I put the image against a grey background to check. As can be seen, the cmap in the axes is transparent while the one in the colorbar is not.
While the colorbar resides inside an axes, it has an additional background patch associated with it. This is white by default and will not be taken into account when transparent=True is used inside of savefig.
A solution is hence to remove the facecolor of this patch manually,
cb.patch.set_facecolor("none")
A complete example, which shows this without actually saving the figure
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
x = np.random.random((10, 10))
colors = [(1,1,1,0), (0,0,0,1)]
cm = LinearSegmentedColormap.from_list('custom', colors, N=256, gamma=0)
fig, ax = plt.subplots(facecolor="grey")
im = ax.pcolor(x,cmap=cm)
cb = fig.colorbar(im, drawedges=False)
ax.set_facecolor("none")
cb.patch.set_facecolor("none")
plt.show()
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'y':['a','b','c','d','e','f','g','h','i']\
,'x':[10,9,9,8,7,6,10,6,7]})
df.sort_values(by='x',inplace=True,ascending = True)
plt.barh(bottom=list(range(1,10)), width=df.x, height = 0.15, align='center',color = 'blue')
plt.xlim([0,11])
plt.yticks(list(range(1,10)),skills.y)
plt.show()
This code gives me a horizontal bar graph.
I want to add a circular dot at the edge of each bars.
Can someone please help me with that.
Tableau graph
I did this in tableau, I want to replicate the same in python.
Also, please let me know if there a better way of coding the same.
I am using Anaconda Python 3.5, Matplotlib library, Windows 10, Idlex IDE
You could just add a scatterplot on top of your bars, using matplotlib scatter function.
Also, note that you could use the numpy.arange function to generate your x values, instead of your current list(range(1,10)).
See example below
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame({'y':['a','b','c','d','e','f','g','h','i'],
'x':[10,9,9,8,7,6,10,6,7]})
df.sort_values(by='x',inplace=True,ascending = True)
plt.barh(bottom=np.arange(len(df)), width=df.x, height = 0.15, align='center',color = 'blue')
plt.scatter(df.x.values, y=np.arange(df.shape[0]), color='b', s=40)
plt.xlim([0,11])
plt.yticks(np.arange(len(df)),df.y)
plt.show()
I'd like to change the spacing of the horizontal grid lines on a seaborn chart, I've tried setting the style with no luck:
seaborn.set_style("whitegrid", {
"ytick.major.size": 0.1,
"ytick.minor.size": 0.05,
'grid.linestyle': '--'
})
bar(range(len(data)),data,alpha=0.5)
plot(avg_line)
The gridlines are set automatically desipite me trying to overide the tick size
Any suggestions? Thanks!
you can set the tick locations explicitly later, and it will draw the grid at those locations.
The neatest way to do this is to use a MultpleLocator from the matplotlib.ticker module.
For example:
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
sns.set_style("whitegrid", {'grid.linestyle': '--'})
fig,ax = plt.subplots()
ax.bar(np.arange(0,50,1),np.random.rand(50)*0.016-0.004,alpha=0.5)
ax.yaxis.set_major_locator(ticker.MultipleLocator(0.005))
plt.show()
The OP asked about modifying tick distances in Seaborn.
If you are working in Seaborn and you use a plotting feature that returns an Axes object, then you can work with that just like any other Axes object in matplotlib. For example:
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
from matplotlib.ticker import MultipleLocator
df = sm.datasets.get_rdataset("Guerry", "HistData").data
ax = sns.scatterplot('Literacy', 'Lottery', data=df)
ax.yaxis.set_major_locator(MultipleLocator(10))
ax.xaxis.set_major_locator(MultipleLocator(10))
plt.show()
Put if you are working with one of the Seaborn processes that involve FacetGrid objects, you will see precious little help on how to modify the tick marks without manually setting them. You have dig out the Axes object from the numpy array inside FacetGrid.axes .
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import MultipleLocator
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, )
g.axes[0][0].yaxis.set_major_locator(MultipleLocator(3))
Note the double subscript required. g is a FacetGrid object, which holds a two-dimensional numpy array of dtype=object, whose entries are matplotlib AxesSubplot objects.
If you are working with a FacetGrid that has multiple axes, then each one will have to be extracted and modified.