Change color to a single point in plotly scatter 3D - plotly-python

I made a plotly 3D scatter:
fig = px.scatter_3d(data, x = x, y = y, z = z, color=data['A'],
color_continuous_scale=px.colors.diverging.Spectral_r,
color_continuous_midpoint= 0,
hover_data=(['B','C']))
And added another single point:
fig.add_scatter3d(x = [0], y= [0], z=[0], mode='markers', color='white')
However, color = 'white', does not work.
ValueError: Invalid property specified for object of type plotly.graph_objs.Scatter3d: 'color'
Any idea on how I can change the color of that single point?

I found this to work ok:
fig.add_scatter3d(x = [0], y= [0], z=[0], mode='markers',marker=dict(color='white'),showlegend=False)
or
fig.add_scatter3d(x = [0], y= [0], z=[0], mode ='markers',marker_color='white',showlegend=False)

Related

Is there a way to propelly align the two yAxis

The problem is the y_h = 1 is not aligned properly with the y = 0.3 and so on, how do i fix this? Below i left a picture of the problem im facing and the code.
yaxis's not aligned
x = 2
y = np.array([0.3, 0.11, 0.43])
y_h = np.array([1, 2, 3])
fig, host = plt.subplots(figsize=(8, 5))
fig.subplots_adjust(right=0.75)
colormap = plt.get_cmap("gist_rainbow")
colors = [colormap(i) for i in np.linspace(0, 1, y.size)]
line = host.twinx()
#plot the lines the give them colors and labels
for i in range(y.size):
p = line.plot([x - x, x], [y_h[i], y[i]], color=colors[i], label="p"+str(i))
#append the line labels to a list
'''for i in range(y.size):
pis.append('p'+str(i))'''
host.set_xlim(0, x)
host.set_ylim(0, y_h.size)
line.set_ylim(0, max(y))
host.set_xlabel("Rev_Count")
host.set_ylabel("Value")
line.set_ylabel('Value_Header')
plt.show()

Getting "ValueError: data mapping points must have x in increasing order" when i plot a map

I'm using the function make_colormap to make my own colors and colorbar in a map. Source: Create own colormap using matplotlib and plot color scale
This is the function:
import matplotlib.colors as mcolors
def make_colormap(seq):
"""Return a LinearSegmentedColormap
seq: a sequence of floats and RGB-tuples. The floats should be increasing
and in the interval (0,1).
"""
seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
cdict = {'red': [], 'green': [], 'blue': []}
for i, item in enumerate(seq):
if isinstance(item, float):
r1, g1, b1 = seq[i - 1]
r2, g2, b2 = seq[i + 1]
cdict['red'].append([item, r1, r2])
cdict['green'].append([item, g1, g2])
cdict['blue'].append([item, b1, b2])
return mcolors.LinearSegmentedColormap('CustomMap', cdict)
c = mcolors.ColorConverter().to_rgb
Also i'm defining my range of values with the minimum and maximum value:
vmintmax = min(tmax[['ENE','FEB','MAR','ABR','MAY','JUN','JUL','AGO','SEP','OCT','NOV','DIC']].min()) # the overall minimum
vmaxtmax = max(tmax[['ENE','FEB','MAR','ABR','MAY','JUN','JUL','AGO','SEP','OCT','NOV','DIC']].max()) # the overall maximum
normtmax = plt.Normalize(vmintmax, vmaxtmax) # function that maps the range of tmax to the range [0,1]
And i'm defining my color values:
rvbtmax = make_colormap([c('lime'), c('lime'), normtmax(11), c('forestgreen'), c('forestgreen'),
normtmax(13), c('lightgreen'), c('lightgreen'), normtmax(15), c('lawngreen'),
c('lawngreen'), normtmax(17),c('greenyellow'), c('greenyellow'),normtmax(19),c('yellow'), c('yellow'),
normtmax(21),c('khaki'), c('khaki'),normtmax(23),c('gold'), c('gold'),normtmax(25),
c('goldenrod'), c('goldenrod'),normtmax(27),c('orange'), c('orange'),normtmax(29),c('orangered'), c('orangered'),normtmax(31),
c('red'), c('red'),normtmax(33),c('firebrick'), c('firebrick'),normtmax(35),
c('darkred'), c('darkred')])
Finally i'm plotting my map here:
for mes in ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio',
'Agosto','Septiembre','Octubre','Noviembre','Diciembre']:
data = tmax[['CODIGO', 'LONGITUD', 'LATITUD', mes]]
lons, lats= np.array(data['LONGITUD']), np.array(data['LATITUD'])
tmaxvalores=np.array(data[mes]).astype(int)
fig = plt.figure('map', figsize=(7,7), dpi=200)
ax = fig.add_axes([0.1, 0.12, 0.80, 0.75], projection=ccrs.PlateCarree())
plt.title('\nNormales Climáticas Mensuales de Temperatura Máxima\nMes de'+f' {mes}'+'\nPeríodo 1981-2010\n')
plt.xlabel('LONGITUD')
plt.ylabel('LATITUD')
ax.outline_patch.set_linewidth(0.3)
l = NaturalEarthFeature(category='cultural', name='admin_0_countries', scale='50m', facecolor='none')
ax.add_feature(l, edgecolor='black', linewidth=0.1)
img = ax.scatter(lons, lats, s=7, c=tmaxvalores, cmap=rvbtmax, norm=normtmax,
marker='o', transform=ccrs.PlateCarree())
But when im plotting the map i get this error: ValueError: data mapping points must have x in increasing order
I have no idea why i get this error. With similar df's and same code i don't get this error.
Would you mind to help me?
Thanks in advance.

Plotting points with different colors using corresponding list of labels

I have the following matrix and vector of labels:
The idea is to plot the points within points according to the labels (1 and -1) in y. assume the calculation of the function true_label works.
M = [5, 10, 15, 25, 70]
for m in M:
points = np.random.multivariate_normal(np.zeros(2), np.eye(2), m)
true_labels = true_label(points)
y = np.where(true_labels, 1, -1)
fig, ax = plt.subplots(1, 1)
colors = ['green', 'red', 'blue']
plt.plot(points, c=y, cmap=matplotlib.colors.ListedColormap(colors))
# red is 1, blue is -1
plt.show()
However I can't seem to get this to work..
AttributeError: Unknown property cmap
is what I keep getting. I've updated matplotlib so I dont really understand why this doesnt work. Any advice on how to get this done easily?

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.

Matplotlib: Scatterplot and heatmap in the same plot

I'm trying to do a scatterplot and heatmap in the same plot.
The scatterplot is as follows:
examples, targets = zip(*list(blue_data()))
examples2, targets2 = zip(*list(red_data()))
plt.plot(np.array(examples), np.array(targets), 'o', color = 'b')
plt.plot(np.array(examples2), np.array(targets2), 'o', color = 'r')
The above works just fine. I also want to do a heatmap. It works just fine, if I do it in a separate subplot. However, I want to try to do both on the same plot, sharing the same axes and am unsure how to do it. This is the code for the heatmap:
x = np.linspace(lower_x, upper_x, 100)
y = np.linspace(lower_y, upper_y, 100)
X, Y = np.meshgrid(x, y)
Z = np.zeros((x.size,y.size))
for ii in range(len(x)):
for jj in range(len(y)):
X_ = X[ii,jj];
Y_ = Y[ii,jj];
Z[ii,jj] = some_function(X_,Y_)
cmap = mpl.colors.ListedColormap(['r', 'b'])
bounds = [-100,0,100]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
plt.imshow(Z,cmap= cmap, norm = norm, extent = [-lower_x,upper_x,-lower_y,upper_y], origin = 'lower');
How can I combine the two plots so that they appear on the same plot with aligned axes?