Matplotlib cmap - custom color definition - python

I am plotting a graph using matplotlib.
Here is the code:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_title("Grid search results - " + model_name)
ax.set_xlabel("Log10(Wight decay)")
ax.set_ylabel("Log10(Learning rate)")
ax.set_zlabel("Batch size")
ax.set_xticks(weightdecay)
ax.set_yticks(learningrate)
ax.set_zticks(trainbatchsize)
scat_plot = ax.scatter(xs=weightdecay, ys=learningrate, zs=trainbatchsize, c=f1, cmap="bwr")
ax.text(top_score[0], top_score[1], top_score[2], top_score[3], color="black")
cb = plt.colorbar(scat_plot, pad=0.2)
cb.ax.set_xlabel('F1 score')
plt.plot(top_score[0], top_score[1], top_score[2], marker="o", markersize=15, markerfacecolor="yellow")
path = Path(output_dir)
plt.savefig(str(path.absolute()) + '/grid_search_plot_' + model_name + ".pdf")
plt.show()
The graph I am getting looks like:
What I would like to do is to use a more granular color-bar. For example for my F1-score (colour-bar), show in:
color1 scores < 0.5
color2 scores 0.5 - 0.75
color3 scores 0.75 - 0.80
color4 scores 0.8 - 0.85
color5 scores 0.85-1
I was trying to re-use some code to create a custom cmap but nothing was working as expected.

One cheap/quick solution might be to create a "categorical color value", like this:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap
import numpy as np
N = 40
x = np.random.uniform(0, 1, N)
y = np.random.uniform(0, 1, N)
z = np.random.uniform(0, 1, N)
# color values
c = np.random.uniform(0, 1, N)
# new color values
new_col = c.copy()
new_col[c < 0.5] = 0
new_col[(c >= 0.5) & (c < 0.75)] = 1
new_col[(c >= 0.75) & (c < 0.8)] = 2
new_col[(c >= 0.8) & (c < 0.85)] = 3
new_col[c >= 0.85] = 4
new_col = new_col / new_col.max()
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
scatter = ax.scatter(x, y, z, c=new_col, cmap=cm.get_cmap("tab10", 5))
cb = fig.colorbar(scatter)
cb.ax.set_yticklabels([0, 0.5, 0.75, 0.80, 0.85, 1])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
EDIT to accommodate comments. The following should be able to deal with cases in which a category doesn't have any element:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap
import numpy as np
N = 40
x = np.random.uniform(0, 1, N)
y = np.random.uniform(0, 1, N)
z = np.random.uniform(0, 1, N)
# color values
c = np.random.uniform(0, 1, N)
# number of categories
NC = 5
# new color values
new_col = c.copy()
new_col[c < 0.5] = 0
new_col[(c >= 0.5) & (c < 0.75)] = 1
new_col[(c >= 0.75) & (c < 0.8)] = 2
new_col[(c >= 0.8) & (c < 0.85)] = 3
new_col[c >= 0.85] = 4
new_col = new_col / NC
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
cmap = ListedColormap(["red", "green", "blue", "magenta", "cyan"])
scatter = ax.scatter(x, y, z, c=cmap(new_col))
cb = fig.colorbar(cm.ScalarMappable(cmap=cmap))
cb.ax.set_yticks(np.linspace(0, 1, NC+1), [0, 0.5, 0.75, 0.80, 0.85, 1])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)

Related

Plot confidence interval of a duration series

I measured the duration of 6000 requests.
I got now an Array of 6000 elements. Each element represents the duration of a connection request in milliseconds.
[3,2,2,3,4,2,2,4,2,3,3,4,2,4,4,3,3,3,4,3,2,3,5,5,2,4,4,2,2,2,3,5,3,2,2,3,3,3,5,4........]
I want to plot the confidence interval in Python and in a clearly arranged manner.
Do you have any Idea how I should plot them?
From what I understood this code should answer your question
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from statistics import NormalDist
X = np.random.sample(100)
data = ((X - min(X)) / (max(X) - min(X))) * 3 + 3
confidence_interval = 0.95
def getCI(data, ci):
normalDist = NormalDist.from_samples(data)
z = NormalDist().inv_cdf((1 + ci) / 2.)
p = normalDist.stdev * z / ((len(data) - 1) ** .5)
return normalDist.mean, normalDist.mean - p, normalDist.mean + p
avg, lower, upper = getCI(data, confidence_interval)
sns.set_style("whitegrid")
plt.figure(figsize=(8, 4))
sns.histplot(data, bins = 10)
plt.axvspan(lower, upper, facecolor='r', alpha=0.2)
plt.axvline(avg, color = 'b', label = 'Average')
plt.ylabel("Operations")
plt.xlabel("Connection Request Duration (ms)")
plt.show()
For boxplot:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from statistics import NormalDist
X = np.random.sample(100)
data = ((X - min(X)) / (max(X) - min(X))) * 3 + 3
confidence_interval = 0.95
def getCI(data, ci):
normalDist = NormalDist.from_samples(data)
z = NormalDist().inv_cdf((1 + ci) / 2.)
p = normalDist.stdev * z / ((len(data) - 1) ** .5)
return normalDist.mean, normalDist.mean - p, normalDist.mean + p
avg, lower, upper = getCI(data, confidence_interval)
sns.set_style("whitegrid")
plt.figure(figsize=(8, 4))
sns.boxplot(data = data, orient = "h")
plt.axvspan(lower, upper, facecolor='r', alpha=0.4)
plt.axvline(avg, color = 'b', label = 'Average')
plt.ylabel("Operations")
plt.xlabel("Connection Request Duration (ms)")
plt.yticks([0],["Server Retry Request Delay"])
plt.savefig("fig.png")
plt.show()
For Multiple Plots:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from statistics import NormalDist
X1, X2 = np.random.sample(100), np.random.sample(100)
data1, data2 = ((X1 - min(X1)) / (max(X1) - min(X1))) * 3 + 3, ((X2 - min(X2)) / (max(X2) - min(X2))) * 2 + 3
confidence_interval = 0.95
def getCI(data, ci):
normalDist = NormalDist.from_samples(data)
z = NormalDist().inv_cdf((1 + ci) / 2.)
p = normalDist.stdev * z / ((len(data) - 1) ** .5)
return normalDist.mean, normalDist.mean - p, normalDist.mean + p
sns.set_style("whitegrid")
avg1, lower1, upper1 = getCI(data1, confidence_interval)
avg2, lower2, upper2 = getCI(data2, confidence_interval)
fig = plt.figure(figsize=(12, 6))
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, sharex = ax1, sharey = ax1)
sns.boxplot(data = data1, orient = "h", ax = ax1)
ax1.axvspan(lower1, upper1, facecolor='r', alpha=0.4)
ax1.axvline(avg1, color = 'b', label = 'Average')
sns.boxplot(data = data2, orient = "h", ax = ax2)
ax2.axvspan(lower2, upper2, facecolor='r', alpha=0.4)
ax2.axvline(avg2, color = 'b', label = 'Average')
ax2.set_xlabel("Connection Request Duration (ms)")
plt.setp(ax1.get_xticklabels(), visible=False)
plt.setp(ax1.get_yticklabels(), visible=False)
plt.setp(ax2.get_yticklabels(), visible=False)
fig.text(0.08, 0.5, "Operations", va='center', rotation='vertical')
plt.show()

Setting value for x-axis and y-axis

I have a code like this, and it will present a figure with the x-axis from 1 to 200, and the y-axis also from 1 to 200. But I would like to make the two axes both from -1.5 to 1.5 with 0.5 space.
I have already tried "plt.xticks" and "set_xlim", but I still cannot make it.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.stats import multivariate_normal
fig, main_ax = plt.subplots(figsize=(5, 5))
divider = make_axes_locatable(main_ax)
top_ax = divider.append_axes("top", 1.05, pad=0.1,sharex=main_ax)
top_ax.xaxis.set_tick_params(labelbottom=False)
main_ax.set_xlabel('dim 1')
main_ax.set_ylabel('dim 2')
top_ax.set_ylabel('Z profile')
x, y = np.mgrid[-1:1:.01, -1:1:.01]
pos = np.empty(x.shape + (2,))
pos[:, :, 0] = x; pos[:, :, 1] = y
rv = multivariate_normal([-0.2, 0.2], [[1, 1.5], [0.25, 0.25]])
z = rv.pdf(pos)
z_max = z.max()
plt.set_cmap(plt.cm.gist_earth)
cur_x = 100
cur_y = 100
main_ax.imshow(z, origin='lower')
main_ax.autoscale(enable=False)
top_ax.autoscale(enable=False)
top_ax.set_ylim(top=z_max)
v_line = main_ax.axvline(cur_x, color='r')
h_line = main_ax.axhline(cur_y, color='y')
v_prof, = top_ax.plot(np.arange(x.shape[1])[::-1], z[:,int(cur_x)], 'r-')
h_prof, = top_ax.plot(np.arange(x.shape[0]), z[int(cur_y),:], 'y-')
plt.show()
You can simply use this code.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.stats import multivariate_normal
fig, main_ax = plt.subplots(figsize=(5, 5))
divider = make_axes_locatable(main_ax)
top_ax = divider.append_axes("top", 1.05, pad=0.1,sharex=main_ax)
top_ax.xaxis.set_tick_params(labelbottom=False)
main_ax.set_xlabel('dim 1')
main_ax.set_ylabel('dim 2')
top_ax.set_ylabel('Z profile')
x, y = np.mgrid[-1:1:.01, -1:1:.01]
pos = np.empty(x.shape + (2,))
pos[:, :, 0] = x; pos[:, :, 1] = y
rv = multivariate_normal([-0.2, 0.2], [[1, 1.5], [0.25, 0.25]])
z = rv.pdf(pos)
z_max = z.max()
plt.set_cmap(plt.cm.gist_earth)
# For y axis
main_ax.set_yticks(np.linspace(0,200,7))
main_ax.set_yticklabels(np.linspace(-1.5,1.5,7))
# For x axis
plt.xticks(np.linspace(0,200,7),np.linspace(-1.5,1.5,7))
cur_x = 100
cur_y = 100
main_ax.imshow(z, origin='lower')
main_ax.autoscale(enable=False)
top_ax.autoscale(enable=False)
top_ax.set_ylim(top=z_max)
v_line = main_ax.axvline(cur_x, color='r')
h_line = main_ax.axhline(cur_y, color='y')
v_prof, = top_ax.plot(np.arange(x.shape[1])[::-1], z[:,int(cur_x)], 'r-')
h_prof, = top_ax.plot(np.arange(x.shape[0]), z[int(cur_y),:], 'y-')

aligning axes of different plots in matplotlib

I am trying to align these plots so the x axis of the top plot perfectly aligns with the x axis values of the imshow. I'm able to do this by setting the aspect to auto, but then my image is warped. is there a way to do this?
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10, 10, 1200)
y = np.linspace(-20, 20, 1600)
xv, yv = np.meshgrid(x, y)
w = 3
xpos = 0
ypos = 5
z = np.exp(-((xv - xpos)**2 + (yv - ypos)**2) / w**2)
xh = np.linspace(0, 2)
yh = np.sin(xh)
sumvertical = np.sum(z, 0)
xvert = range(np.shape(z)[1])
sumhoriz = np.sum(z, 1)
yhoriz = range(np.shape(z)[0])
# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left + width + 0.02
rect_scatter = [left, bottom, width, height]
rect_x = [left, bottom_h, width, 0.2]
rect_y = [left_h, bottom, 0.2, height]
plt.figure(1, figsize=(8, 8))
axCenter = plt.axes(rect_scatter)
axhoriz = plt.axes(rect_x)
axvert = plt.axes(rect_y)
axCenter.imshow(z, origin='lower', cmap='jet') #aspect='auto')
axhoriz.plot(xvert, sumvertical)
axvert.plot(sumhoriz, yhoriz)
plt.show()
I would recommend using the tools from mpl_toolkits.axes_grid1, namely make_axes_locatable to divide the center axes to leave room for the marginal axes.
You should then also set the margins to 0 along the shared direction to have the ranges match up.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
x = np.linspace(-10, 10, 1200)
y = np.linspace(-20, 20, 1600)
xv, yv = np.meshgrid(x, y)
w = 3
xpos = 0
ypos = 5
z = np.exp(-((xv - xpos)**2 + (yv - ypos)**2) / w**2)
xh = np.linspace(0, 2)
yh = np.sin(xh)
sumvertical = np.sum(z, 0)
xvert = range(np.shape(z)[1])
sumhoriz = np.sum(z, 1)
yhoriz = range(np.shape(z)[0])
fig, axCenter = plt.subplots(figsize=(8, 8))
fig.subplots_adjust(.05,.1,.95,.95)
divider = make_axes_locatable(axCenter)
axvert = divider.append_axes('right', size='30%', pad=0.5)
axhoriz = divider.append_axes('top', size='20%', pad=0.25)
axCenter.imshow(z, origin='lower', cmap='jet')
axhoriz.plot(xvert, sumvertical)
axvert.plot(sumhoriz, yhoriz)
axhoriz.margins(x=0)
axvert.margins(y=0)
plt.show()

Heatmap widget in matplotlib

I'm creating the heat map of a function with tuneable exponent. Here is my code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
from matplotlib.colors import LogNorm
alpha0 = 2.
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
bining = np.logspace(1, 10, 1000)
x = y = bining
X, Y = np.meshgrid(x, y)
Z = [[0 for i in xrange(len(x) - 1)] for j in xrange(len(y) - 1) ]
for i in xrange(len(x) - 1):
for j in xrange(len(y) - 1):
Z[i][j] = 1./((x[i]+y[j])**(2+alpha0))
Z = np.array(Z)
im = plt.pcolormesh(X,Y,Z, cmap = plt.cm.Spectral, norm=LogNorm())
plt.xscale('log')
plt.yscale('log')
plt.axes().set_aspect('equal')
axcolor = 'lightgoldenrodyellow'
axexp = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
sexp = Slider(axexp, r"$\alpha$", 0.1, 10.0, valinit=alpha0)
def update(val):
alpha = sexp.val
Z = [[0 for i in xrange(len(x) - 1)] for j in xrange(len(y) - 1) ]
for i in xrange(len(x) - 1):
for j in xrange(len(y) - 1):
Z[i][j] = 1./((x[i]+y[j])**(2+alpha))
Z = np.array(Z)
plt.pcolormesh(X,Y,Z, cmap = plt.cm.Spectral, norm=LogNorm())
fig.canvas.draw_idle()
sexp.on_changed(update)
It creates the figure and the slider, but when I try to change the exponent value, the heat map is not affected.
So my question, why is it not working and how can I solve it ? Also, widgets can be saved ? In what format ? Eventually I would use in a Beamer (LaTeX) presentation.
Thank you !

Bulls eye plot of image

I want to plot the Bull's Eye diagram of an image. I tried these codes
Shade 'cells' in polar plot with matplotlib
For Bull's Eye diagram I want to use different colors. Is there is any way to set this colors? In color = choice(['navy','maroon','lightgreen']) colors are repeating according as for loop iterates.
Does anyone know if in matplotlib there is a function correponding to matlab bullseye()?
To provide something similar to the matlab function you mentioned, I drafted some code (shared on git hub as well) for the creation of bullseyes with any number of sector for each radial subdivision. The colour is given by the colormap and by the values below the sector. Moreover, this allows for the modification the centering of the radial subdivision.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker
def bulls_eye(ax, data, cmap=None, norm=None, raidal_subdivisions=(2, 8, 8, 11),
centered=(True, False, False, True), add_nomenclatures=True, cell_resolution=128,
pfi_where_to_save=None, colors_bound='-k'):
"""
Clockwise, from smaller radius to bigger radius.
:param ax:
:param data:
:param cmap:
:param norm:
:param raidal_subdivisions:
:param centered:
:param add_nomenclatures:
:param cell_resolution:
:param pfi_where_to_save:
:return:
"""
line_width = 1.5
data = np.array(data).ravel()
if cmap is None:
cmap = plt.cm.viridis
if norm is None:
norm = mpl.colors.Normalize(vmin=data.min(), vmax=data.max())
theta = np.linspace(0, 2*np.pi, 768)
r = np.linspace(0, 1, len(raidal_subdivisions)+1)
nomenclatures = []
if isinstance(add_nomenclatures, bool):
if add_nomenclatures:
nomenclatures = range(1, sum(raidal_subdivisions)+1)
elif isinstance(add_nomenclatures, list) or isinstance(add_nomenclatures, tuple):
assert len(add_nomenclatures) == sum(raidal_subdivisions)
nomenclatures = add_nomenclatures[:]
add_nomenclatures = True
# Create the circular bounds
line_width_circular = line_width
for i in range(r.shape[0]):
if i == range(r.shape[0])[-1]:
line_width_circular = int(line_width / 2.)
ax.plot(theta, np.repeat(r[i], theta.shape), colors_bound, lw=line_width_circular)
# iterate over cells divided by radial subdivision
for rs_id, rs in enumerate(raidal_subdivisions):
for i in range(rs):
cell_id = sum(raidal_subdivisions[:rs_id]) + i
theta_i = - i * 2 * np.pi / rs + np.pi / 2
if not centered[rs_id]:
theta_i += (2 * np.pi / rs) / 2
theta_i_plus_one = theta_i - 2 * np.pi / rs # clockwise
# Create colour fillings for each cell:
theta_interval = np.linspace(theta_i, theta_i_plus_one, cell_resolution)
r_interval = np.array([r[rs_id], r[rs_id+1]])
angle = np.repeat(theta_interval[:, np.newaxis], 2, axis=1)
radius = np.repeat(r_interval[:, np.newaxis], cell_resolution, axis=1).T
z = np.ones((cell_resolution, 2)) * data[cell_id]
ax.pcolormesh(angle, radius, z, cmap=cmap, norm=norm)
# Create radial bounds
if rs > 1:
ax.plot([theta_i, theta_i], [r[rs_id], r[rs_id+1]], colors_bound, lw=line_width)
# Add centered nomenclatures if needed
if add_nomenclatures:
if rs == 1 and rs_id ==0:
cell_center = (0, 0)
else:
cell_center = ((theta_i + theta_i_plus_one) / 2., r[rs_id] + .5 * r[1] )
if isinstance(nomenclatures[0], (int, long, float, complex)):
ax.annotate(r"${:.3g}$".format(nomenclatures[cell_id]), xy=cell_center,
xytext=(cell_center[0], cell_center[1]),
horizontalalignment='center', verticalalignment='center', size=8)
else:
ax.annotate(nomenclatures[cell_id], xy=cell_center,
xytext=(cell_center[0], cell_center[1]),
horizontalalignment='center', verticalalignment='center', size=12)
ax.grid(False)
ax.set_ylim([0, 1])
ax.set_yticklabels([])
ax.set_xticklabels([])
if pfi_where_to_save is not None:
plt.savefig(pfi_where_to_save, format='pdf', dpi=200)
def multi_bull_eyes(multi_data, cbar=None, cmaps=None, normalisations=None,
global_title=None, canvas_title='title', titles=None, units=None, raidal_subdivisions=(2, 8, 8, 11),
centered=(True, False, False, True), add_nomenclatures=(True, True, True, True),
pfi_where_to_save=None, show=True):
plt.clf()
n_fig = len(multi_data)
if cbar is None:
cbar = [True] * n_fig
if cmaps is None:
cmaps = [mpl.cm.viridis] * n_fig
if normalisations is None:
normalisations = [mpl.colors.Normalize(vmin=np.min(multi_data[i]), vmax=np.max(multi_data[i]))
for i in range(n_fig)]
if titles is None:
titles = ['Title {}'.format(i) for i in range(n_fig)]
h_space = 0.15 / n_fig
h_dim_fig = .8
w_dim_fig = .8 / n_fig
def fmt(x, pos):
# a, b = '{:.2e}'.format(x).split('e')
# b = int(b)
# return r'${} \times 10^{{{}}}$'.format(a, b)
return r"${:.4g}$".format(x)
# Make a figure and axes with dimensions as desired.
fig = plt.figure(figsize=(3 * n_fig, 4))
fig.canvas.set_window_title(canvas_title)
if global_title is not None:
plt.suptitle(global_title)
for n in range(n_fig):
origin_fig = (h_space * (n + 1) + w_dim_fig * n, 0.15)
ax = fig.add_axes([origin_fig[0], origin_fig[1], w_dim_fig, h_dim_fig], polar=True)
bulls_eye(ax, multi_data[n], cmap=cmaps[n], norm=normalisations[n], raidal_subdivisions=raidal_subdivisions,
centered=centered, add_nomenclatures=add_nomenclatures[n])
ax.set_title(titles[n], size=10)
if cbar[n]:
origin_cbar = (h_space * (n + 1) + w_dim_fig * n, .15)
axl = fig.add_axes([origin_cbar[0], origin_cbar[1], w_dim_fig, .05])
cb1 = mpl.colorbar.ColorbarBase(axl, cmap=cmaps[n], norm=normalisations[n], orientation='horizontal',
format=ticker.FuncFormatter(fmt))
cb1.ax.tick_params(labelsize=8)
if units is not None:
cb1.set_label(units[n])
if pfi_where_to_save is not None:
plt.savefig(pfi_where_to_save, format='pdf', dpi=330)
if show:
plt.show()
if __name__ == '__main__':
# Very dummy data:
data = np.array(range(29)) + 1
# TEST bull-eye three-fold
if True:
fig, ax = plt.subplots(figsize=(12, 8), nrows=1, ncols=3,
subplot_kw=dict(projection='polar'))
fig.canvas.set_window_title('Left Ventricle Bulls Eyes')
# First one:
cmap = mpl.cm.viridis
norm = mpl.colors.Normalize(vmin=1, vmax=29)
bulls_eye(ax[0], data, cmap=cmap, norm=norm)
ax[0].set_title('Bulls Eye ')
axl = fig.add_axes([0.14, 0.15, 0.2, 0.05])
cb1 = mpl.colorbar.ColorbarBase(axl, cmap=cmap, norm=norm, orientation='horizontal')
cb1.set_label('Some Units')
# Second one
cmap2 = mpl.cm.cool
norm2 = mpl.colors.Normalize(vmin=1, vmax=29)
bulls_eye(ax[1], data, cmap=cmap2, norm=norm2)
ax[1].set_title('Bulls Eye ')
axl2 = fig.add_axes([0.41, 0.15, 0.2, 0.05])
cb2 = mpl.colorbar.ColorbarBase(axl2, cmap=cmap2, norm=norm2, orientation='horizontal')
cb2.set_label('Some other units')
# Third one
cmap3 = mpl.cm.winter
norm3 = mpl.colors.Normalize(vmin=1, vmax=29)
bulls_eye(ax[2], data, cmap=cmap3, norm=norm3)
ax[2].set_title('Bulls Eye third')
axl3 = fig.add_axes([0.69, 0.15, 0.2, 0.05])
cb3 = mpl.colorbar.ColorbarBase(axl3, cmap=cmap3, norm=norm3, orientation='horizontal')
cb3.set_label('Some more units')
plt.show()
if True:
fig = plt.figure(figsize=(5, 7))
fig.canvas.set_window_title('Bulls Eyes - segmentation assessment')
# First and only:
cmap = mpl.cm.viridis
norm = mpl.colors.Normalize(vmin=1, vmax=29)
ax = fig.add_axes([0.1, 0.2, 0.8, 0.7], polar=True)
bulls_eye(ax, data, cmap=cmap, norm=norm)
ax.set_title('Bulls Eye')
axl = fig.add_axes([0.1, 0.15, 0.8, 0.05])
cb1 = mpl.colorbar.ColorbarBase(axl, cmap=cmap, norm=norm, orientation='horizontal')
cb1.set_label('Some Units')
plt.show()
if True:
multi_data = [range(1,17), list( 0.000000001 * np.array(range(1,17))), list( 0.001 * np.array(range(1,17)))]
print multi_data
multi_bull_eyes(multi_data, raidal_subdivisions=(3,3,4,6),
centered=(True, True, True, True), add_nomenclatures=[True]*3)
plt.show(block=True)
It is proposed within my code LabelsManager on github, that you are welcome to use.
Here is an example, for raidal_subdivisions=(2, 8, 8, 11), and centered=(True, False, False, True):
I don't think that there is a specific bullseye method in matplotlib, but comparing what the matlab function does and the right plot in this answer, I think that you should be able to get what you want playing a bit with the radius coordinates. E.g. (borrowing from the aforesaid answer)
import numpy as np
import matplotlib.pyplot as plt
theta, r = np.mgrid[0:2*np.pi:20j, 0.2:1:10j]
z = np.random.random(theta.size).reshape(theta.shape)
fig, ax = plt.subplots(ncols=1, subplot_kw=dict(projection='polar'))
ax.pcolormesh(theta, r, z)
ax.set_yticklabels([])
ax.set_ylim([0, 1])
plt.show()
plots
I don't understand exactly what you mean with the question about the colors. ax.pcolormesh accept either a colormap or a matplotlib color. If you want specific colors you can play with those two parameters and/or create your own colormap.

Categories

Resources