python colormap quantisation (matplotlib) - python-3.x

I have the following colormap in Python which maps each value to a color. But my question: How can I quantize the values for getting a same color for a specified range?
For example: from 0 until 10 (Green) ,
from 10 until 50 (yellow),
from 50 until 55 (red) , ...
import matplotlib as mpl
import matplotlib
from matplotlib import cm
.
.
.
norm = matplotlib.colors.Normalize(vmin = min,vmax = max, clip = True)
.
.
for i in range(numberMaterials):
step = (max-min)/numberMaterials
value = min + step*i
mat = bpy.data.materials.new("mat" +str(i))
color = cm.jet(norm(value),bytes=True)

It seems you are asking for a BoundaryNorm.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
cmap = matplotlib.colors.ListedColormap(["limegreen", "gold", "crimson"])
norm = matplotlib.colors.BoundaryNorm([0,10,50,55], 3)
x = np.linspace(0,55)
fig, (ax, ax2) = plt.subplots(ncols=2)
sc = ax.scatter(x,x, c=x, cmap=cmap, norm=norm)
fig.colorbar(sc, ax=ax, spacing="uniform")
sc2 = ax2.scatter(x,x, c=x, cmap=cmap, norm=norm)
fig.colorbar(sc2, ax=ax2, spacing="proportional")
plt.show()

Related

How to add a hovering annotation on a bar plot with mplcursors

How can I modify this plot to show me the value of each bar upon hovering mouse?
sns.barplot(x = "date", y = "no_of_dogs", data = dogs_adopted_per_day, palette="husl")
plt.show()
You could employ mplcursors as follows:
import matplotlib.pyplot as plt
import mplcursors
import numpy as np
import pandas as pd
import seaborn as sns
df = pd.DataFrame({"date": pd.date_range('20210101', periods=10),
"no_of_dogs": np.random.randint(10, 30, 10)})
fig, ax = plt.subplots(figsize=(15, 5))
sns.barplot(x="date", y="no_of_dogs", data=df, palette="husl", ax=ax)
x_dates = df['date'].dt.strftime('%Y-%m-%d')
ax.set_xticklabels(labels=x_dates)
cursor = mplcursors.cursor(hover=True)
#cursor.connect("add")
def on_add(sel):
x, y, width, height = sel.artist[sel.target.index].get_bbox().bounds
sel.annotation.set(text=f"{x_dates[round(x)]}\n{height:.0f}",
position=(0, 20), anncoords="offset points")
sel.annotation.xy = (x + width / 2, y + height)
plt.show()

Arrow is not plotted

Why is the first arrow not plotted? There is no error after running the script. There should be three arrows but there are only two arrows. Thank you
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
import math
import matplotlib.patches as patches
# Plot figure with size
fig, ax = plt.subplots(sharex=True, sharey=True, figsize=(5,5))
# Axis - lim
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
shift = 0.011
length = 1.3
coord_45 = math.sqrt(1/2)
# Plot an arrow
style="Simple,tail_width=0.5,head_width=4,head_length=8"
kw = dict(arrowstyle=style)
a3 = patches.FancyArrowPatch((0, 0.366618), (0.211427, 0.211427),connectionstyle="arc3,rad=10", **kw)
ax.scatter(0, 0, marker = 'o', s=30)
arrow = mpatches.FancyArrowPatch((0, 0-shift), (0, length), arrowstyle=style)
plt.gca().add_patch(arrow)
arrow = mpatches.FancyArrowPatch((0, 0), (coord_45, -coord_45), arrowstyle=style)
plt.gca().add_patch(arrow)
plt.savefig('file.pdf')
plt.show()

Plotting colorbar in Python 3

I am trying to color the errorbar points based on the color from an array. But getting an error. My code is shown below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable, coolwarm as cmap
from matplotlib.colors import Normalize
fig = plt.figure(1)
sp = fig.add_subplot(1, 1, 1)
sp.set_xlabel(r'$x$')
sp.set_ylabel(r'$y$')
x = np.random.rand(10)
y = np.random.rand(10)
M = np.logspace(9, 10, 10)
norm = Normalize(vmin=8, vmax=11,clip=False) # controls the min and max of the colorbar
smap = ScalarMappable(cmap=cmap, norm=norm)
for xi, yi, Mi in zip(x, y, M):
c = cmap(norm(np.log10(Mi))) # make sure to color by log of mass, not mass
sp.errorbar(
xi,
yi,
yerr=[[.1], [.1]],
xerr=[[.1], [.1]],
ecolor=c,
marker='o',
mec=c,
mfc=c
)
cb = plt.colorbar(smap)
cb.set_label(r'$\log_{10}M$')
I am getting the following error:
TypeError: You must first set_array for mappable
For matplotlib < 3.1, you need to set an array - which can be empty
sm = ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
fig.colorbar(sm)
For matplotlib >= 3.1, this is not necessary any more.
sm = ScalarMappable(cmap=cmap, norm=norm)
fig.colorbar(sm)

Can't plot anything with matplotlib

Whenever I try to plot something with matplotlib, I get the following error:
File "C:\Users\username\AppData\Local\Programs\Python\Python37-32\Lib\tkinter\__init__.py", line 2018, in __init__
baseName = os.path.basename(sys.argv[0])
builtins.IndexError: list index out of range
For example, i've tried the following code:
import matplotlib.pyplot as plt
import numpy as np
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radii
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()
I have the latest version of matplotlib, please help.
Thank you
You need to import numpy.
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radii
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()

Axis label missing

I am trying to create a 3D plot but I am having trouble with the z-axis label. It simply doesn't appear in the graph. How do I amend this? The code is as follows
# Gamma vs Current step 2
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
h = np.arange(0.1,5.1,0.1)
gamma = np.arange(0.1,5.1,0.1)
sigmaz_hgam = np.array([.009998,.03988,.08878,.15403
,.230769,.312854,.394358,.4708311,.539697879,.6,.6518698
,.696033486,.73345752165,.7651390123,.792,.814845635
,.8343567,.851098499,.865535727,.8780487,.8889486,.89848986
,.906881,.914295,.9208731,.9267338,.93197569,.93668129
,.9409202379,.94475138,.951383,.9542629,.956895,.959309
,.961526,.9635675,.96545144,.9671934,.968807,.97030539
,.9716983,.972995,.974206,.975337,.97639567,.977387,.978318
,.97919266,.98,.9807902])
mu = 1
sigmaz_hgam = mu*sigmaz_hgam
# creates an empty list for current values to be stored in
J1 = []
for i in range(sigmaz_hgam.size):
expec_sz = sigmaz_hgam[i]
J = 4*gamma[i]*(mu-expec_sz)
J1.append(J.real)
#print(J)
This part of the code is what is used to graph out which is where the problem lies
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
x = h
y = gamma
z = J1
ax.plot(x, y, z, label='Dephasing Model')
ax.legend()
ax.set_xlabel('h', fontsize=10)
ax.set_ylabel('$\gamma$')
ax.yaxis._axinfo['label']['space_factor'] = 3.0
for t in ax.zaxis.get_major_ticks(): t.label.set_fontsize(10)
# disable auto rotation
ax.zaxis.set_rotate_label(False)
ax.set_zlabel('J', fontsize=10, rotation = 0)
plt.show()
On my version of Matplotlib (2.0.2), on a Mac, I see the label (which is there – most of it is just being cropped out of the image in your case).
You could try to reduce the padding between the ticks and the label:
ax.zaxis.labelpad = 0

Resources