colorbar with plotly in r - marker

I got some trouble to set up the color of the colorbar in plotly
Here is the part of my script :
else if(is.na(pmatch("NGVS",limits[,ii]))&(max_value==min_value)){
if (max_value==0){
m<-list(
colorbar = list(title = ii),
size = 20, symbol = 'square',cmin=0,cmax=limits[,ii])
mypalette=rev(rainbow(100,
start=rgb2hsv(col2rgb('blue'))[1], end=rgb2hsv(col2rgb('yellow'))[1]))
p = plot_ly(graph3,x=Sampling.Date,y=Yaxis.,type="scatter",
color=param_to_plot,colors= mypalette,mode="markers",marker = m)
p = layout(p,yaxis = a, xaxis=b, autosize = F, width = 700, height = 700, margin = q)
print(p)
rm(p)
What I want is to set up the colors of the colorbar to green to yellow. And as the points are all zeros they should all be green. For now, I only got a red colorscale from grey to red with all the points grey. And I don't know how to fix it up. Thanks for your help

Related

How do we align marker and text in legends vertically in Matplotlib?

When the marker in a legend is a dot, dot and text are not aligned vertically. To solve this I tried following:
l = ax.legend()
for text in l.texts:
text.set_va('center') # Is there some setting for this in matplotlibrc, too??
plt.show()
The vertical alignment of text in a legend seems to be baseline. But no matter whether I choose center, bottom or baseline, etc., things are off:
Zooming in, this is what Matplotlib gives us out of the box:
What I want is also what other software like Inkscape gives me, when aligning two objects vertically:
Can Matplotlib do this for me/us?
This appears to work:
Set it to display only a single scatterpoint per legend entry by setting scatterpoints=1 in the call to legend()
Set the vertical offset of this point to 0 by setting scatteryoffsets=[0] in the call to legend()
After creating the legend, iterate through its text labels and set their vertical alignment to center_baseline, using for t in l.get_texts(): t.set_va('center_baseline')
figure(figsize=(2,2))
scatter([0],[0],marker='s',s=20,label='Thing 1')
scatter([1],[0],marker='s',s=20,label='t')
scatter([2],[0],marker='s',s=20,label='T¹₁')
l = legend(scatterpoints=1,scatteryoffsets=[0],handletextpad=-0.5)
for t in l.get_texts(): t.set_va('center_baseline')
Here is what I do:
import numpy as np
import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
matplotlib.rc('text', usetex = True)
from matplotlib import pyplot as py
## setup figure
figure = py.figure(figsize = (7.5, 5.0))
axs = [py.subplot(1, 1, 1)]
## make plot
xs = np.linspace(0.0, np.pi, 100)
ys = np.sin(xs)
axs[0].plot(xs, ys, color = 'dodgerblue', label = r'$n = 1$')
ys = np.sin(2.0 * xs)
axs[0].plot(xs, ys, color = 'seagreen', label = r'$n = 2$')
axs[0].axhline(0.0, color = 'gray', linestyle = 'dashed')
## vertical alignment
legends = axs[0].legend(frameon = False, fontsize = 25, loc = 'lower left')
shift = np.average([_.get_window_extent(renderer = figure.canvas.get_renderer()).height for _ in legends.get_texts()])
shift /= 3.6
for _ in legends.get_texts():
_.set_va('center') ## va is alias for verticalalignment
_.set_position((0, shift))
## save figure
name = 'test.pdf'
py.tight_layout()
py.savefig(name)
py.close()
It is, however, complicated and requires manual adjustments,
I am still looking for better solutions.

misalignment between grid cells and color mesh used to highlight them (in Matplotlib)

I am using the following code to to generate this heat map:
dim = np.arange(1, 32, 1)
fig, ax = plt.subplots(figsize=(7,9))
heatmap = ax.imshow(h, aspect=1, cmap=plt.cm.get_cmap('Blues', 5), clim=[0,100])
ax.set_ylabel("Days", fontsize=15)
ax.set_xlabel("Months", fontsize=15)
ax.set_title("Percentage of records per day", fontsize=18)
ax.set_yticks(range(0,31))
ax.set_yticklabels(dim, ha='center', minor=False)
ax.set_xticks(range(0,13,1))
ax.set_xticklabels(ylabel[7:],rotation=45, ha='right')
ax.grid(which = 'minor', color = 'w')
ax.set_facecolor('gray')
ax.xaxis.set_minor_locator(MultipleLocator(.5))
ax.yaxis.set_minor_locator(MultipleLocator(.5))
cbaxes = fig.add_axes([.8, .35, .04, .3])
cbar = fig.colorbar(heatmap, ticks = [0, 20, 40, 60, 80 ,100], label = 'Percentage', cax = cbaxes)
fig.show()
I would like to highlight all of the cells with a value greater or equal to 60.
I tried adding this to my code:
highlight = (h> 60)
highlight = np.ma.masked_less(highlight, 1)
ax.pcolormesh(highlight, facecolor = 'None')
and got this:
I am almost there but the cells and the mesh are misaligned. How could I fix this?
The cells in a heatmap are centered on integers, this means for example that the cell with index 0,0 is in fact -0.5 to 0.5 on both axes. You have to subtract 0.5 to the coordinates of your highlights.
Thanks to mozway's comment I was able to fix my problem. I changed the beginning of my code to:
highlight = (h> 60)
highlight = np.ma.masked_less(highlight, 1)
x = np.arange(-0.5,12,1) # len = 10
y = np.arange(-0.5,30,1) # len = 6
X, Y = np.meshgrid(x, y)
and change the line plotting the color mesh to:
ax.pcolormesh(x,y,highlight, facecolor = 'None', edgecolors = 'w',shading='auto', zorder=2)
I also had to set the z-order of the color mesh to be greater than the grid lines (zorder=2 and zorder=1 respectively).

Standard Plot size in Python-matplotlib

I am generating multiple plots using matplotlib.patches.rect depending on the requirements. Some cases 2 rectangles are plotted sometimes 4 rectangles. But the visualisation size differs depending on the numbers of such rectangles although the dimensions of rectangles remains the same. Here in my case every rectangle has fixed shape (1200X230).
Below is the entire working code:
sampledata = {'Layer':[1,2,3,4,5,6], 'Type':[1,1,2,2,2,2]}
ip0 = pd.DataFrame(sampledata, columns=['Layer','Type'])
for i in range(ip0['Type'].nunique()):
fig = plt.figure()
ax = fig.add_subplot(111)
ip = ip0[ip0['Type']== i+1]
b = i+1
ax.grid(linestyle='--',linewidth = '0.3', color = 'black')
for i in range(ip['Layer'].nunique()):
y_pos = (i*300)
r = matplotlib.patches.Rectangle(xy=(0, y_pos), width=1201,height=233,
facecolor = None, edgecolor = 'red', linewidth=1.2, fill = False)
ax.text(-230, y_pos+175, 'Layer-{}'.format(i),
color='g',rotation='vertical', fontsize= (36/ip['Layer'].nunique()))
ax.add_patch(r)
plt.xlim([0, 1500])
plt.ylim([0, (ip['Layer'].nunique()*300)])
plt.savefig(f'image_bin_{b}.jpeg',bbox_inches='tight', dpi =
1600,transparent=True)
I have attached pictures of 2 cases one where there 2 rectangles and one 4. Please help me making them look similar since the actual dimensions are equal.

Shapefile zooming to plot with geopandas

I have a shapefile of Italy and I'm plotting the GIS Data on it. Thing is I've got a small trajectory of a bus going within a city(Rome) and when i`m plotting, it appears like 1 dot. I guess because of my map.
How to zoom the map (.shp) ?
street_map = gpd.read_file("roads.shp")
...
...
fig,ax = plt.subplots(figsize = (20,15))
street_map.plot(ax = ax, alpha = 0.4, color = "grey")
geo_df[geo_df['Perc_'] > 25].plot(ax = ax, markersize = 20, color = "blue",
marker = "o", label = "Neg")
geo_df[geo_df['Perc_'] < 25].plot(ax = ax, markersize = 20, color = "red",
marker = "^", label = "Pos")
plt.legend(prop={'size':15})
Based on your 1st image, it is possible to get the zoom-in plot by specifying proper x and y limits.
...
ax.set_ylim([40.4, 47.2])
ax.set_xlim([7.0, 14.4])
(Place this code before plt.legend().
Hope this is useful.

Change markerfacecolor for some of the markers in Matplotlib

I have a plot that shows markers in a circle. I want to be able to change the colour of 3 of them. I've tried using a variable for markerfacecolor as follows but that doesn't work:
angle = 0.0
colorR = 'red'
angleUpdate = 2 * numpy.pi / (len(v.T))
for i in range(len(v.T)):
x = numpy.sin(angle)
y = numpy.cos(angle)
angle += angleUpdate
if i < 3:
colorR = 'green'
v[0, i] = x
v[1, i] = y
plt.plot(v[0], v[1], 'ko', markerfacecolor = colorR, markersize = 70, clip_on = False)
plt.show()
Is there a way of doing this?
In your plot 'ko' means put a black circle marker; k stands for black. You should try:
plt.plot(v[0], v[1], 'o', markerfacecolor = 'red')
To get the abbreviation of other symbols and colors try:
help(plt.plot)
You can either achieve your case using plot or scatter, depending on what you are doing:
import pylab as plt
x=[1,2,3,4,5,6,7,8,9,10]
plt.plot(x[:5],x[:5],'o',c='r',markersize=10)
plt.plot(x[5:],x[5:],'o',c='b',markersize=10)
plt.show()
will generate,
Similarly, you can also use
plt.scatter(x[:5],x[:5],c='r',s=100)
plt.scatter(x[5:],x[5:],c='b',s=100)