Is it possible to change the text color of the cbar legend values ? We want to use a black background but the text is falling away. We use Matplotlib for plotting.
We can change the text color of the label, but not of the values.
cbar = m.colorbar(cs,location='right',pad="10%")
cbar.set_label('dBZ', color="white")
Thank you in advanced.
Kevin Broeren
You can change the color of the color bar values using set_yticklabels since they are tick labels for the color bar axis. Here's an example:
import matplotlib.pyplot as plt
from numpy.random import randn
# plot something
fig, ax = plt.subplots()
cax = ax.imshow(randn(100,100))
# create the color bar
cbar = fig.colorbar(cax)
cbar.set_label('dBZ', color = "white")
# update the text
t = cbar.ax.get_yticklabels();
labels = [item.get_text() for item in t]
cbar.ax.set_yticklabels(labels, color = 'white')
plt.show()
The first answer to this question has an explanation of why you need to do it this way.
Related
I am trying to use different colors for axes background color and figure background color using the matplotlib and seaborn. I got the following graph.
sns.set(rc = {'axes.facecolor': 'yellow', 'figure.facecolor': 'red'})
plt.figure(figsize = (6,6))
sns.scatterplot(x = x, y = y, data = df)
plt.show()
But I don't want those whitegrid lines and want ticks under the axes and called sns.set_style('ticks').
sns.set(rc = {'axes.facecolor': 'yellow', 'figure.facecolor': 'red'})
plt.figure(figsize = (6,6))
sns.set_style('ticks')
sns.scatterplot(x = x, y = y, data = df)
plt.show()
I got the ticks as I wanted but the axes background color is not coming as I set in 'axes.facecolor': 'yellow'. Why is this happening? How can I set the ticks and get the specified background color with no grid lines?
Also how can I adjust the width of the figure background color so that the red color strip in the above diagram is of equal width on all 4 sides?
The axes.facecolor is part of the style definition, so if you want to use a seaborn style but also override some of its parameters, you need to do both at the same time:
sns.set_theme(style='ticks', rc={'axes.facecolor': 'yellow', 'figure.facecolor': 'red'})
plt.figure(figsize=(6,6))
sns.scatterplot(x=x, y=y, data=df)
plt.show()
Note that I switched sns.set to sns.set_theme; they are aliases and do the same thing but set_theme is the preferred interface and sns.set will likely be deprecated at some point in the future.
I have the below plot, however, I am struggling with the 3 questions below....
How can I move X-axis labels (1-31) to the top of the plot?
How can I change formating of the color bar from (7000 to 7k etc.)
How can I change the color from gray to another cmap like "Reds"?
Can I change the figure size? plt.figure(figsize=(20,10)) does not work?
data1 = pd.read_csv("a2data/data1.csv")
data2 = pd.read_csv("a2data/data2.csv")
merged_df = pd.concat([data1, data2])
merged_df.set_index(['month', 'day'], inplace=True)
merged_df.sort_index(inplace=True)
merged_df2=merged_df.groupby(['month', 'day']).deaths.mean().unstack('day')
plt.imshow(merged_df2)
plt.xticks(np.arange(merged_df2.shape[1]), merged_df2.columns)
plt.yticks(np.arange(merged_df2.shape[0]), merged_df2.index)
plt.colorbar(orientation="horizontal")
plt.show()
Let's try:
# create a single subplot to access the axis
fig, ax = plt.subplots()
# passing the `cmap` for custom color
plt.imshow(df, cmap='hot', origin='upper')
# draw the colorbar
cb = plt.colorbar(orientation="horizontal")
# extract the ticks on colorbar
ticklabels = cb.get_ticks()
# reformat the ticks
cb.set_ticks(ticklabels)
cb.set_ticklabels([f'{int(x//1000)}K' for x in ticklabels])
# move x ticks to the top
ax.xaxis.tick_top()
plt.show()
Output:
Try this to invert the y axis:
ax = plt.yticks(np.arange(merged_df2.shape[0]), merged_df2.index)
plt.colorbar(orientation="horizontal")
ax.invert_yaxis()
plt.show()
I think for the color, you can find better in the pyplot documentation, https://matplotlib.org/3.3.1/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot
I make a boxplot with matplotlib:
import pandas as pd
import matplotlib.pyplot as plt
A = pd.DataFrame([54.183933149245775,98.14228839908178,97.56790596547185,81.28351460722497,116.36733517668105,93.64706288367272,107.68860349692736,109.65565349602194,88.58717530217115,54.87561132504807,137.89097514410435,116.90021701471281,121.41252555476005,102.68420408219474,107.32642696333856,
120.27307064490907,114.3674635060443,91.38936314166017,149.0476109186976,121.76625219213736,155.6027360469248,115.86331915425764,99.35036421024546,104.93804853361358,115.64286896238708,129.51583078514085,116.30239399660411,97.58582728510798,119.59975852978403,103.68594428632996], columns=['A'])
fig, ax = plt.subplots(1,1)
A.boxplot(grid=False, fontsize=12, notch=True,
flierprops = dict(markersize=10, markeredgecolor ='red', markerfacecolor='b'),
boxprops = dict(linewidth=2, color='red'))
fig.show()
The flier props will change the colors and marker size. However, for "boxprops", the linewidth can change but the color NEVER changes (here it stays blue). Does anybody know why? Also, where is the matplotlib documentation giving all the options for these properties?
You can do that by doing two things actually,
First, determine the return_type of your boxplot
Second, change the color of the boxes key like so:
Here, I will change the boxes into green
import pandas as pd
import matplotlib.pyplot as plt
A = pd.DataFrame([54.183933149245775,98.14228839908178,97.56790596547185,81.28351460722497,116.36733517668105,93.64706288367272,107.68860349692736,109.65565349602194,88.58717530217115,54.87561132504807,137.89097514410435,116.90021701471281,121.41252555476005,102.68420408219474,107.32642696333856,
120.27307064490907,114.3674635060443,91.38936314166017,149.0476109186976,121.76625219213736,155.6027360469248,115.86331915425764,99.35036421024546,104.93804853361358,115.64286896238708,129.51583078514085,116.30239399660411,97.58582728510798,119.59975852978403,103.68594428632996], columns=['A'])
fig, ax = plt.subplots(1,1)
bp = A.boxplot(grid=False, fontsize=12, notch=True,
flierprops = dict(markersize=10, markeredgecolor ='red', markerfacecolor='b'),
boxprops = dict(linewidth=2, color='red'),
return_type='dict') # add this argument
# set the color of the boxes to green
for item in bp['boxes']:
item.set_color('g')
plt.show()
And this will show the following graph:
Values in my matrix called 'energy' are close enough to each other: e.g. one value can be 500, another one 520. And i want to see the color difference on my plot more precisely. Like for the smallest value in my data it should be the very dark color and for the highest value it should be the very bright color.
I have the following code:
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
plt.imshow(energy[0:60, 0:5920], cmap='Reds')
ax.axes.set_aspect(aspect=100)
plt.grid(color='yellow')
plt.title('My plot')
plt.xlabel('Length points')
plt.ylabel('Time points(seconds)')
import matplotlib.ticker as plticker
loc = plticker.MultipleLocator(base=500)
ax.xaxis.set_major_locator(loc)
plt.show()
I get the following plot:
plot of energy
Other words i'd love to get this plot more colorful.
Thanks in advance.
You can set a custom range either through a custom colormap or adjusting the range value to show using the keywords vmin and vmax. For example:
from matplotlib.pyplot import subplots
import numpy as np
fig, ax = subplots()
h = ax.imshow(np.random.rand(10,10) * 10, vmin = 0,\
vmax = 2, cmap = 'Reds')
fig.colorbar(h)
fig.show()
Which produces the colors within 0, 2 value
Alternatively you can rescale your data or adjust your colormap, see the maplotlib docs for more info.
Context: Matplotlib scatter plots.
When using transparency (alpha<1) in scatter plots and an axis background color other than white, the colors in the corresponding colorbar look different. This is clearly visible in the figure below: The colorbar on the right looks "too bright". However, setting the background color of the axis of the colorbar does not change this.
So the question: How can I change the background color of colorbar with transparent colors?
I'm using Python 2.7.3 and Matplotlib 1.3.1 (on Ubuntu 12.04)
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(10) #for reproducability
n = 10
ticks = range(n)
data = np.hstack((np.random.rand(50,2),np.random.randint(0,n,(50,1))))
colors = plt.cm.get_cmap('jet',n)(ticks)
lcmap = plt.matplotlib.colors.ListedColormap(colors)
plt.figure(figsize=(8,4))
ax = plt.subplot(121)
plt.scatter(data[:,0],data[:,1], c=data[:,2], s=40, alpha=0.3,
edgecolor='none', cmap=lcmap)
plt.colorbar(ticks=ticks)
plt.clim(-0.5,9.5)
ax = plt.subplot(122)
plt.scatter(data[:,0],data[:,1], c=data[:,2], s=40, alpha=0.3,
edgecolor='none', cmap=lcmap)
cb = plt.colorbar(ticks=ticks)
ax.set_axis_bgcolor((0.2,0.2,0.2))
cb.ax.set_axis_bgcolor((0.2,0.2,0.2))
plt.clim(-0.5,9.5)
plt.show()
Put this line after your plt.clim call,
cb.patch.set_facecolor((0.2, 0.2, 0.2, 1.0))