Related
I was trying to get a map projection using cartopy in python and it wasn't made so I'm trying to piece it together using to subplots with the following code:
fig = plt.figure(figsize =(25,13),facecolor='white')
gs = fig.add_gridspec(1,2,width_ratios=[4,2],height_ratios = [1], hspace=0.2,wspace=.0)
ax1=fig.add_subplot(gs[0,0],projection=ccrs.PlateCarree())
ax2=fig.add_subplot(gs[0,1],projection=ccrs.PlateCarree())
ax2.set_extent([-180,0,-90,90])
ax1.set_extent([-180,180,-90,90])
ax1.add_feature(cfeature.LAND, color = 'lightgray')
ax2.add_feature(cfeature.LAND, color = 'lightgray')
ax1.add_feature(cfeature.COASTLINE)
ax2.add_feature(cfeature.COASTLINE)
and I get the right projection I was looking for, however I am trying to remove the line between the two subplots and I keep getting issues, any suggestions?
Your question is a challenge as it is uncommon to plot a map with longitude extent greater than 360 degrees. What you have done is already a good achievement. What I will do just to finish your work.
Here is the code that produces the plot you need.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
#from shapely.geometry import Point, Polygon
import cartopy.feature as cfeature
import matplotlib.transforms as transforms
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
fig = plt.figure(figsize =(25,9.5), facecolor='white')
gs = fig.add_gridspec(1, 2, width_ratios=[4,2], height_ratios = [1], hspace=0.2, wspace=.0)
proj = ccrs.PlateCarree(central_longitude=0)
ax1=fig.add_subplot( gs[0,0], projection=proj )
ax2=fig.add_subplot( gs[0,1], projection=proj )
ax1.set_extent([-179.9, 180, -90, 90]) #Tricky, -180 not works!
ax2.set_extent([-179.9, 0, -90, 90])
ax1.add_feature(cfeature.LAND, color = 'lightgray')
ax2.add_feature(cfeature.LAND, color = 'lightgray')
ax1.add_feature(cfeature.COASTLINE)
ax2.add_feature(cfeature.COASTLINE)
# Set color of ax2's boundaries
# If set 'white' the gridline at that position will be gone!
ax2.outline_patch.set_edgecolor('lightgray') # set color to match other gridlines
# Draw 3 sides boundaries of ax2
# ------------------------------
# Define a `transformation`
# Signature: blended_transform_factory(x_transform, y_transform)
# the y coords of this transformation are data (as is = ax.transData)
# but the x coord are axes coordinate (0 to 1, ax.transAxes)
transAD = transforms.blended_transform_factory(ax2.transAxes, ax2.transData)
# Plot 3 lines around extents of ax2
# Color is intentionally set as 'red'
# You need to change it to 'black' for your work
ax2.plot([0.996, 0.996], [-90, 90], color='red', lw=2, transform=transAD)
ax2.plot([0.0, 0.996], [-90, -90], color='red', lw=2, transform=transAD)
ax2.plot([0.0, 0.996], [89.6, 89.6], color='red', lw=2, transform=transAD)
gl1 = ax1.gridlines(ccrs.PlateCarree(),
xlocs=range(-180,181,20),
ylocs=range(-90,90,10),
linestyle='-',
y_inline=False, x_inline=False,
color='b', alpha=0.6, linewidth=0.25, draw_labels=True)
gl1.xformatter = LONGITUDE_FORMATTER
gl1.yformatter = LATITUDE_FORMATTER
gl1.right_labels = False
gl2 = ax2.gridlines(ccrs.PlateCarree(),
xlocs=range(-180,180,20),
ylocs=range(-90,90,10),
linestyle='-',
y_inline=False, x_inline=False,
color='b', alpha=0.6, linewidth=0.25, draw_labels=True)
gl2.xformatter = LONGITUDE_FORMATTER
gl2.yformatter = LATITUDE_FORMATTER
gl2.left_labels = False
I am creating a 2D matplotlib plot (i and j coordinates) which contains 10 subplots. Each subplot contains 150 by 150 grid cell data. How can I insert a small black-colored square mark (3 by 3 ) somewhere fixed (center at coordinates 62 and 62 ) on each generated heatmap sub-plot across those 10 sub-plots? The square mark would therefore contain 10 blocks from 60 to 64 in both x and y direction and contains a written text "Sale 1" centered at x 62 and y 62. My code below does not generate any patches. Any feedback is greatly appreciated.
from matplotlib.patches import Rectangle
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score, median_absolute_error
import os
import matplotlib.cm as cm
from mpl_toolkits import axes_grid1
import matplotlib.pyplot as plt
#import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.colors
import matplotlib.colors as colors
data = np.random.rand(10, 150, 150)
data = data.reshape(-1, 1)
property = "Sale"
pmin = data.min()
pmax = data.max()
v = np.linspace(round(pmin,3), round(pmax,3),15, endpoint=True)
v = [round(x,3) for x in v]
fig, ax = plt.subplots(2, 5, figsize=(160, 80))
row_count = 0
col_count = 0
for i in range(10):
sub_plot_data = data[(i)*(150*150):(i+1)*150*150]
x = 150
y = 150
#--------------------------- Define the map boundary ----------------------
xmin = 1258096.6
xmax = 1291155.0
ymin = 11251941.6
ymax = 11285000.0
pmin = min(sub_plot_data)
pmax = max(sub_plot_data)
# --------------------------- define color bar for Discrete color
bounds = np.linspace(-1, 1, 10)
Discrete_colors = plt.get_cmap('jet')(np.linspace(0,1,len(bounds)+1))
# create colormap without the outmost colors
cmap = mcolors.ListedColormap(Discrete_colors[1:-1]) #
actual_2d = np.reshape(sub_plot_data,(y,x))
im1 = ax[row_count, col_count].imshow(actual_2d, interpolation=None, cmap=cmap,
extent=(xmin, xmax, ymin, ymax), vmin=pmin, vmax=pmax)
plt.text(actual_2d[62, 62], actual_2d[62, 62], '%s' % 'Sale_1',
horizontalalignment='center', verticalalignment='center', color= 'black', fontsize= 90)
ax[row_count, col_count].set_title("Sale_Stores-%s - L: %s"%(i+1, layer),
fontsize=130, pad=44, x=0.5, y=0.999) # new
ax[row_count, col_count].set_aspect('auto')
ax[row_count, col_count].tick_params(left=False, labelleft=False, top=False,
labeltop=False, right=False, labelright=False, bottom=False, labelbottom=False) # new
#ax[row_count, col_count] = plt.gca()
plt.gca().add_patch(Rectangle((60, 60), 3, 3, edgecolor='black',
facecolor='black',fill=True,lw=2))
ax[row_count, col_count].add_patch(plt.text(62, 62, '%s' % 'Sale_1',
horizontalalignment='center', verticalalignment='center', color= 'black', fontsize= 90))
col_count +=1
if col_count == 5:
row_count +=1
col_count =0
fig.tight_layout(h_pad=10)
plt.subplots_adjust(left=0.02,
bottom=0.1,
right=0.91,
top=0.8,
wspace=0.1,
hspace=0.2)
cbaxes = fig.add_axes([0.94, 0.05, 0.02, 0.8])
cbar = fig.colorbar(im1, ax=ax.ravel().tolist(), ticks=v, extend='both', cax =cbaxes)
cbar.ax.tick_params(labelsize=70)
#cbar.set_ticks(v)
cbar.ax.set_yticklabels([i for i in v], fontsize=120)
output_dir = r"D/test"
plot_dir = os.path.join(output_dir, reservoir_property)
if not os.path.exists(plot_dir):
os.makedirs(plot_dir)
fig.savefig(r"%s/per_allmodel.png"%(plot_dir))
I tried your code and made a couple of modifications: first, the graph size was too huge and caused errors, so I made it smaller; second, I simplified the subplots: axes has a list of subplot objects, so I took them out with axes.flat; third The second is modifying the text as annotations. The graph size has been reduced and the font size and spacing have been adjusted, so please modify it yourself. Finally, tick_params is not set since the color bar ticks are disabled.
fig, axes = plt.subplots(2, 5, figsize=(16, 8))
row_count = 0
col_count = 0
for i,ax in enumerate(axes.flat):
sub_plot_data = data[(i)*(150*150):(i+1)*150*150]
x = 150
y = 150
#--------------------------- Define the map boundary ----------------------
xmin = 1258096.6
xmax = 1291155.0
ymin = 11251941.6
ymax = 11285000.0
pmin = min(sub_plot_data)
pmax = max(sub_plot_data)
# --------------------------- define color bar for Discrete color
bounds = np.linspace(-1, 1, 10)
Discrete_colors = plt.get_cmap('jet')(np.linspace(0,1,len(bounds)+1))
# create colormap without the outmost colors
cmap = mcolors.ListedColormap(Discrete_colors[1:-1]) #
actual_2d = np.reshape(sub_plot_data,(y,x))
#im = ax.imshow(actual_2d, interpolation=None, cmap=cmap, extent=(xmin, xmax, ymin, ymax), vmin=pmin, vmax=pmax)
im = ax.imshow(actual_2d, interpolation=None, cmap=cmap)
ax.text(actual_2d[62, 62], actual_2d[62, 62]-10, '%s' % 'Sale_1',
horizontalalignment='center', verticalalignment='center', color= 'black', fontsize=18)
ax.set_title("Sale_Stores-%s - L: %s"%(i+1, 1), fontsize=14, pad=30, x=0.5, y=0.999)
ax.set_aspect('auto')
ax.add_patch(Rectangle((60, 60), 6, 6, edgecolor='red', facecolor='red', fill=True, lw=2))
ax.text(62, 62, '%s' % 'Sale_1', ha='center', va='center', color='black', fontsize=14)
fig.tight_layout(h_pad=10)
plt.subplots_adjust(left=0.02,
bottom=0.1,
right=0.91,
top=0.8,
wspace=0.1,
hspace=0.5)
cbaxes = fig.add_axes([0.94, 0.05, 0.02, 0.8])
cbar = fig.colorbar(im, ax=axes.flat, ticks=v, extend='both', cax=cbaxes)
cbar.ax.tick_params(labelsize=10)
#cbar.set_ticks(v)
cbar.ax.set_yticklabels([str(i) for i in v], fontsize=12)
#plt.tick_params(left=False, labelleft=False, top=False, labeltop=False, right=False, labelright=False, bottom=False, labelbottom=False)
plt.show()
I try to produce a plot and want to automatically add text (in this case is percentage) to each circle in correspond to each y axis types. Any help would be very helpful.
# import libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
# Make some data
index=['Stream flow',
'Soil moisture',
'Water indices',
'Others',
'Temperature',
'Precipitation',
'Vegetative indices']
value=[2.13, 6.38, 10.64, 12.77, 17.73, 21.99, 28.37]
# create dataframe
percentages = pd.Series(value,index=index)
df = pd.DataFrame({'percentage' : percentages})
df = df.sort_values(by='percentage')
# we first need a numeric placeholder for the y axis
my_range=list(range(1,len(df.index)+1))
fig, ax = plt.subplots(figsize=(15,8))
# create for each expense type an horizontal line that starts at x = 0 with the length
plt.hlines(y=my_range, xmin=0, xmax=df['percentage']-0.5, color='black', alpha=0.8, linewidth=1)
# create for each expense type a dot at the level of the expense percentage value
line=plt.plot(df['percentage'], my_range, "o", markersize=30, color='#fd8c00', alpha=0.6, linewidth=0.3)
# set labels
ax.set_xlabel('Percentage', fontsize=15)
ax.set_ylabel('')
# set axis
ax.tick_params(axis='both', which='major', labelsize=14)
plt.yticks(my_range, df.index)
ax.set_xlim(0,30)
You can use matplotlib.axes.Axes.text:
x_space = 0.4
y_space = 0.05
fontsize = 7
for y_i, val in enumerate(value, 1):
ax.text(x = val - x_space, y = y_i - y_space, s = f'{val}%', fontsize = fontsize)
You have to adjust x_space, y_space and fontsize in order to fit properly the text within the circles.
Complete code
# import libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
# Make some data
index=['Stream flow',
'Soil moisture',
'Water indices',
'Others',
'Temperature',
'Precipitation',
'Vegetative indices']
value=[2.13, 6.38, 10.64, 12.77, 17.73, 21.99, 28.37]
# create dataframe
percentages = pd.Series(value,index=index)
df = pd.DataFrame({'percentage' : percentages})
df = df.sort_values(by='percentage')
# we first need a numeric placeholder for the y axis
my_range=list(range(1,len(df.index)+1))
fig, ax = plt.subplots(figsize=(15,8))
# create for each expense type an horizontal line that starts at x = 0 with the length
plt.hlines(y=my_range, xmin=0, xmax=df['percentage']-0.5, color='black', alpha=0.8, linewidth=1)
# create for each expense type a dot at the level of the expense percentage value
line=plt.plot(df['percentage'], my_range, "o", markersize=30, color='#fd8c00', alpha=0.6, linewidth=0.3)
# set labels
ax.set_xlabel('Percentage', fontsize=15)
ax.set_ylabel('')
# set axis
ax.tick_params(axis='both', which='major', labelsize=14)
plt.yticks(my_range, df.index)
ax.set_xlim(0,30)
x_space = 0.4
y_space = 0.05
for y_i, val in enumerate(value, 1):
ax.text(x = val - x_space, y = y_i - y_space, s = f'{val:>5.2f}%', fontsize = 7)
plt.show()
Same code as above, but with increased circle radius and font, in order to improve readability.
# import libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
# Make some data
index=['Stream flow',
'Soil moisture',
'Water indices',
'Others',
'Temperature',
'Precipitation',
'Vegetative indices']
value=[2.13, 6.38, 10.64, 12.77, 17.73, 21.99, 28.37]
# create dataframe
percentages = pd.Series(value,index=index)
df = pd.DataFrame({'percentage' : percentages})
df = df.sort_values(by='percentage')
# we first need a numeric placeholder for the y axis
my_range=list(range(1,len(df.index)+1))
fig, ax = plt.subplots(figsize=(15,8))
# create for each expense type an horizontal line that starts at x = 0 with the length
plt.hlines(y=my_range, xmin=0, xmax=df['percentage']-0.85, color='black', alpha=0.8, linewidth=1)
# create for each expense type a dot at the level of the expense percentage value
line=plt.plot(df['percentage'], my_range, "o", markersize=50, color='#fd8c00', alpha=0.6, linewidth=0.3)
# set labels
ax.set_xlabel('Percentage', fontsize=15)
ax.set_ylabel('')
# set axis
ax.tick_params(axis='both', which='major', labelsize=14)
plt.yticks(my_range, df.index)
ax.set_xlim(0,30)
ax.set_ylim(0, len(value) + 1)
x_space = 0.75
y_space = 0.06
fontsize = 12
for y_i, val in enumerate(value, 1):
ax.text(x = val - x_space, y = y_i - y_space, s = f'{val:>5.2f}%', fontsize = fontsize)
plt.show()
Even better, you can use matplotlib.axes.Axes.annotate to get rid of x_space and y_space:
fontsize = 12
for y_i, x_i in enumerate(value, 1):
ax.annotate(f'{x_i:>5.2f}%', xy = (x_i, y_i), xytext = (0, 0), textcoords = 'offset points', ha = 'center', va = 'center', fontsize = fontsize)
You still have to adjust the fontsize to properly fit the radius of the circles.
I'm using this code to plot my data in boxplot:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon
random_dists = ['Overlap', 'Non overlap', ]
Overlap= [6,6,5,1,3,4,4,3]
non_overlap= [1,2,6,6,1,3,3,3,3,3,5,2,2]
data = [
Overlap,
non_overlap
]
fig, ax1 = plt.subplots(figsize=(6, 6))
fig.canvas.set_window_title('A Boxplot Example')
fig.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)
# bp = ax1.boxplot(data, notch=0, sym='+', vert=1, whis=1.5)
bp = ax1.boxplot(data)
plt.setp(bp['boxes'], color='black')
plt.setp(bp['whiskers'], color='black')
plt.setp(bp['fliers'], color='red', marker='+')
# Add a horizontal grid to the plot, but make it very light in color
# so we can use it for reading data values but not be distracting
ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',
alpha=0.5)
# Hide these grid behind plot objects
ax1.set_axisbelow(True)
ax1.set_title('overlap and non_overlap against mRS')
# ax1.set_xlabel('Distribution')
# ax1.set_ylabel('Value')
# Now fill the boxes with desired colors
box_colors = ['darkkhaki', 'royalblue']
num_boxes = len(data)
medians = np.empty(num_boxes)
for i in range(num_boxes):
box = bp['boxes'][i]
boxX = []
boxY = []
for j in range(5):
boxX.append(box.get_xdata()[j])
boxY.append(box.get_ydata()[j])
box_coords = np.column_stack([boxX, boxY])
# Alternate between Dark Khaki and Royal Blue
ax1.add_patch(Polygon(box_coords, facecolor=box_colors[i % 2]))
# Now draw the median lines back over what we just filled in
med = bp['medians'][i]
medianX = []
medianY = []
for j in range(2):
medianX.append(med.get_xdata()[j])
medianY.append(med.get_ydata()[j])
ax1.plot(medianX, medianY, 'k')
medians[i] = medianY[0]
# Finally, overplot the sample averages, with horizontal alignment
# in the center of each box
ax1.plot(np.average(med.get_xdata()), np.average(data[i]),
color='w', marker='*', markeredgecolor='k')
# Set the axes ranges and axes labels
ax1.set_xlim(0.5, num_boxes + 0.5)
top = 10 #y-axis
bottom = 0 #y-axis
ax1.set_ylim(bottom, top)
ax1.set_xticklabels(np.repeat(random_dists, 1),
rotation=45, fontsize=8)
pos = np.arange(num_boxes) + 1
# Finally, add a basic legend
fig.text(0.80, 0.08, 'Overlap',
backgroundcolor=box_colors[0], color='black', weight='roman',
size='x-small')
fig.text(0.80, 0.045, 'Non overlap',
backgroundcolor=box_colors[1],
color='white', weight='roman', size='x-small')
fig.text(0.80, 0.015, '*', color='white', backgroundcolor='silver',
weight='roman', size='medium')
fig.text(0.815, 0.013, ' Average Value', color='black', weight='roman',
size='x-small')
plt.show()
What i need is overlap the data into it as a scatter plot just like the picture from this link
I really try hard to use the code on the link and try to search on overstack to find a solution but i'm not that good in coding, also i try using seaborn library but i always get an error that: 'list' object has no attribute 'get' and couldn't fix it
so please any one can help ()
The current version of plt.boxplot() allows plotting most of these elements standard.
Means will be drawn if showmeans is set to True. Its properties can be controlled via the meanprops dictionary. When setting patch_artist=True, instead of just the outline, a filled box will be drawn, boxprops controls how they look.
To draw the scatter plot on top, just call ax1.scatter. The x-positions can be jittered randomly via i + np.random.uniform(-0.4, 0.4). To force them on top of boxplot, their z-order can be changed.
As the fliers are also part of the scatter data, it probably makes sense to leave them out (showfliers=False).
To create a legend, you can collect handles to all desired elements and pass them to ax1.legend(). Note that your boxplots already get labels in the x-axis, so having them also in the legend might be a bit superfluous.
import matplotlib.pyplot as plt
import numpy as np
random_dist_names = ['Overlap', 'Non overlap']
overlap = [6, 6, 5, 1, 3, 4, 4, 3]
non_overlap = [1, 2, 6, 6, 1, 3, 3, 3, 3, 3, 5, 2, 2]
data = [overlap, non_overlap]
fig, ax1 = plt.subplots(figsize=(6, 6))
fig.canvas.set_window_title('A Boxplot Example')
fig.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)
box_colors = ['darkkhaki', 'royalblue']
scatter_colors = ['purple', 'crimson']
legend_handles = []
for i, (values, box_color, scatter_color) in enumerate(zip(data, box_colors, scatter_colors), start=1):
bp = ax1.boxplot(values, positions=[i], showmeans=True, patch_artist=True, showfliers=False,
boxprops={'edgecolor': 'black', 'facecolor': box_color},
whiskerprops={'color': 'black'}, # flierprops={'color': 'red', 'marker': '+'},
medianprops={'color': 'lime', 'linewidth': 2, 'linestyle': ':'},
meanprops={'markerfacecolor': 'w', 'marker': '*', 'markeredgecolor': 'k', 'markersize': 10})
if i == 1:
legend_handles.append(bp['means'][0])
legend_handles.append(bp['boxes'][0])
ax1.scatter(i + np.random.uniform(-0.4, 0.4, len(values)), values, color=scatter_color, alpha=0.5, zorder=3)
ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)
ax1.set_axisbelow(True)
ax1.set_title('overlap and non_overlap against mRS')
ax1.set_xlim(0.5, len(data) + 0.5)
ax1.set_ylim(ymin=0)
ax1.set_xticklabels(random_dist_names, rotation=0, fontsize=8)
ax1.legend(legend_handles, ['Mean'] + random_dist_names, bbox_to_anchor=[1, -0.1], loc='upper right')
plt.show()
Note that you have very few data points, and they all have integer values, which makes the red dots appear in horizontal lines.
PS: To create something similar with Seaborn, the data has to be organized more similar to a pandas dataframe. Such a dataframe would have one column with all the values, and one column with the category.
The legend can be created more automatically. To also get the means into the legend, a label has to be assigned to the mean via meanprops={..., 'label': 'Mean'}. Unfortunately, this creates one legend entry for every box. These can be skipped by first getting all the legend entries with ax.get_legend_handles_labels() and taking subarrays of the handles and labels.
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
random_dist_names = ['Overlap', 'Non overlap']
overlap = [6, 6, 5, 1, 3, 4, 4, 3]
non_overlap = [1, 2, 6, 6, 1, 3, 3, 3, 3, 3, 5, 2, 2]
data_names = np.repeat(random_dist_names, [len(overlap), len(non_overlap)])
data_values = np.concatenate([overlap, non_overlap])
ax = sns.boxplot(x=data_names, y=data_values, hue=data_names, palette=['darkkhaki', 'royalblue'],
dodge=False, showfliers=False, showmeans=True,
meanprops={'markerfacecolor': 'w', 'marker': '*', 'markeredgecolor': 'k', 'markersize': 10, 'label': 'Mean'})
sns.stripplot(x=data_names, y=data_values, color='red', alpha=0.4)
handles, labels = ax.get_legend_handles_labels()
skip_pos = len(random_dist_names) - 1
ax.legend(handles[skip_pos:], labels[skip_pos:], bbox_to_anchor=(1.02, -0.05), loc='upper right')
plt.tight_layout()
plt.show()
I am doing a correlation matrix using a seaborn heatmap, I need to :
Change the distance between the ticks and the labels of x and y.
Also, change the distance between the title and the heatmap.
Unifying the color of annotation to be either white or black.
I am using the following code:
from matplotlib import pyplot as plt
import matplotlib
import numpy as np
import seaborn as sns
#call data frame and apply correlation:
#data =
#df = pd.DataFrame(data, columns = features)
#df_small = df.iloc[:,:]#if only few parameters are needed
#correlation_mat = df_small.corr()
#Create color pallete:
def NonLinCdict(steps, hexcol_array):
cdict = {'red': (), 'green': (), 'blue': ()}
for s, hexcol in zip(steps, hexcol_array):
rgb =matplotlib.colors.hex2color(hexcol)
cdict['red'] = cdict['red'] + ((s, rgb[0], rgb[0]),)
cdict['green'] = cdict['green'] + ((s, rgb[1], rgb[1]),)
cdict['blue'] = cdict['blue'] + ((s, rgb[2], rgb[2]),)
return cdict
#https://www.december.com/html/spec/colorshades.html
hc = ['#e5e5ff', '#C7DDF2', '#8EBAE5', '#407FB7', '#00549F']#ffffff #e5e5ff
th = [0, 0.25, 0.5, 0.75, 1]
hc = hc[:0:-1] + hc # prepend a reversed copy, but without repeating the central value
cdict = NonLinCdict(np.linspace(0, 1, len(hc)), hc)
cm = matplotlib.colors.LinearSegmentedColormap('test', cdict)
corr=np.random.uniform(-1, 1, (6,6))
#plot correlation matrix:
plt.figure(figsize = (10,8))
ax=sns.heatmap(corr,center=0, linewidths=1, annot = True,cmap=cm ,square=True, vmin=-1, vmax=1,
robust=True, annot_kws={'size':16}, cbar=True,linecolor='#F6A800',xticklabels=True,
yticklabels=True)
cbar = ax.collections[0].colorbar
cbar.ax.tick_params(labelsize=10, axis='both', which='both', length=0)
cbar.set_ticks(np.linspace(-1, 1, 11))
plt.title("title", y=-1.5,fontsize = 18,)
plt.xlabel("X_parameters",fontsize = 18)
plt.ylabel("Y_paramaters",fontsize = 18)
ax.tick_params(axis='both', which='both', length=0)
ax.axhline(y=0, color='#F6A800',linewidth=4)
ax.axhline(y=corr.shape[1], color='#F6A800',linewidth=4)
ax.axvline(x=0, color='#F6A800',linewidth=4)
ax.axvline(x=corr.shape[0], color='#F6A800',linewidth=4)
#change position of lables and titles and assign colors.
plt.show()
My current output is:
Well, plt.title() has a parameter pad= to set the padding between the text of the title and the top spine of the plot (default is 6). plt.xlabel() and plt.ylabel() have a parameter labelpad= to set the distance between the axis label and the ticklabels.
sns.heatmap() has a parameter annot_kws which is a dictionary of parameters for the annotation texts. The color can be changed via sns.heatmap(..., annot_kws={'size': 16, 'color': 'black'}). Note that for readability, seaborn's default uses white for text on the dark-colored cells, and black for the light-colored cells.
from matplotlib import pyplot as plt
import matplotlib
import numpy as np
import seaborn as sns
def NonLinCdict(steps, hexcol_array):
cdict = {'red': (), 'green': (), 'blue': ()}
for s, hexcol in zip(steps, hexcol_array):
rgb = matplotlib.colors.hex2color(hexcol)
cdict['red'] = cdict['red'] + ((s, rgb[0], rgb[0]),)
cdict['green'] = cdict['green'] + ((s, rgb[1], rgb[1]),)
cdict['blue'] = cdict['blue'] + ((s, rgb[2], rgb[2]),)
return cdict
hc = ['#e5e5ff', '#C7DDF2', '#8EBAE5', '#407FB7', '#00549F'] # ffffff #e5e5ff
th = [0, 0.25, 0.5, 0.75, 1]
hc = hc[:0:-1] + hc # prepend a reversed copy, but without repeating the central value
cdict = NonLinCdict(np.linspace(0, 1, len(hc)), hc)
cm = matplotlib.colors.LinearSegmentedColormap('test', cdict)
corr = np.random.uniform(-1, 1, (6, 6))
# plot correlation matrix:
plt.figure(figsize=(10, 8))
ax = sns.heatmap(corr, center=0, linewidths=1, annot=True, cmap=cm, square=True, vmin=-1, vmax=1,
robust=True, annot_kws={'size': 16, 'color': 'black'}, cbar=True, linecolor='#F6A800',
xticklabels=True, yticklabels=True)
cbar = ax.collections[0].colorbar
cbar.ax.tick_params(labelsize=10, axis='both', which='both', length=0)
cbar.set_ticks(np.linspace(-1, 1, 11))
plt.title("title", y=-1.5, fontsize=18, pad=15)
plt.xlabel("X_parameters", fontsize=18, labelpad=15)
plt.ylabel("Y_paramaters", fontsize=18, labelpad=15)
ax.tick_params(axis='both', which='both', length=0)
ax.axhline(y=0, color='#F6A800', linewidth=4)
ax.axhline(y=corr.shape[1], color='#F6A800', linewidth=4)
ax.axvline(x=0, color='#F6A800', linewidth=4)
ax.axvline(x=corr.shape[0], color='#F6A800', linewidth=4)
plt.show()