How To Change Colours In Plotly 3D Scatter - python-3.x

I'm learning how to plot 3D scatters on Plotly using their example with my own data. Sample here
I can get the scatter to plot (it looks so cool) but I can't get the different data series points to appear as separate colours.
import plotly #load plotly for plotting
import plotly.plotly as py
from plotly import tools
from plotly.graph_objs import * #all the types of plots that we will plot here
plotly.offline.init_notebook_mode() # run at the start of every ipython notebook
trace1 = Scatter3d(
x = res,
y = lc,
z = spent,
mode='markers',
marker=dict(
size=12,
color=["z","y","x"], # set color to an array/list of desired values
colorscale='Viridis', # choose a colorscale
opacity=0.8
)
)
data = [trace1]
layout = Layout(
margin=dict(
l=0,
r=0,
b=0,
t=0
)
)
fig = Figure(data=data, layout=layout)
plotly.offline.iplot(fig, filename='3d-scatter-colorscale')
I've tried using other examples for separate sources e.g. Cambridge Spark but I just don't have the experience to figure out how to make it work.
I'm sure it's something simple that I've missed but can't see it.

I should've had one of my series as the marker point. In this case I used spent instead of a list of x, y, z
import plotly #load plotly for plotting
import plotly.plotly as py
from plotly import tools
from plotly.graph_objs import * #all the types of plots that we will plot here
plotly.offline.init_notebook_mode() # run at the start of every ipython notebook
trace1 = Scatter3d(
x = res,
y = lc,
z = spent,
mode='markers',
marker=dict(
size=12,
color=spent, # set color to an array/list of desired values
colorscale='Viridis', # choose a colorscale
opacity=0.8
)
)
data = [trace1]
layout = Layout(
margin=dict(
l=0,
r=0,
b=0,
t=0
)
)
fig = Figure(data=data, layout=layout)
plotly.offline.iplot(fig, filename='3d-scatter-colorscale')

Related

How to highlight current cursor values on X and Y axis in plotly?

I have a plotly chart and whenever I move cursor on it, I want to see corresponding X and Y values being highlighted. How can I achieve that? Below is sample image of how it should look.
(Not a very clear image, but on Y-axis you can see highlighted tickers)
Here's a sample code for a simple plotly plot
import datetime as dt
import panel as pn
import yfinance as yf
pn.extension()
# Data part
vix_tickers = ['AUDJPY=X']
df = yf.download(vix_tickers,
auto_adjust=True, #only download adjusted data
progress=False,
)
df = df[["Close"]]
# A Plot
import plotly.graph_objs as go
fig = go.Figure()
df.sort_index(ascending=True, inplace=True)
trace = go.Scatter(x=list(df.index), y=list(df.Close))
fig.add_trace(trace)
fig.update_layout(
dict(
title="Time series with range slider and selectors",
xaxis=dict(
rangeselector=dict(
buttons=list(
[
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=6, label="6m", step="month", stepmode="backward"),
dict(count=1, label="YTD", step="year", stepmode="todate"),
dict(count=1, label="1y", step="year", stepmode="backward"),
dict(step="all"),
]
)
),
rangeslider=dict(visible=False),
type="date",
),
)
)
fig.show()

plt.legend only adds first element to scatter plot

I am trying to add a legend to my scatter plot with 13 classes, however, with my code below, I am only able to get the first label. Can you assist me in generating the full list to show up in the legend of the scatter plot?
Here is my example code:
from sklearn.datasets import make_blobs
from matplotlib import pyplot
from pandas import DataFrame
# generate 2d classification dataset
X, y = make_blobs(n_samples=1000, centers=13, n_features=2)
classes = [f"class {i}" for i in range(13)]
#fig = plt.figure()
plt.figure(figsize=(15, 12))
scatter = plt.scatter(
x=X[:,0],
y=X[:,1],
s = 20,
c = y,
cmap='Spectral'
#c=[sns.color_palette()[x] for x in y_train_new]
)
plt.gca().set_aspect('equal', 'datalim')
plt.legend(classes)
plt.title('Dataset', fontsize=24)
You can do that by replacing the plt.legend(classes) in your code by this line... I hope this is what you are looking for. I am using matplotlib 3.3.4.
plt.legend(handles=scatter.legend_elements()[0], labels=classes)
Output plot

How to plot Lon/Lat values at the border of a orthographic cartopy plot?

I use some shapefile data of the outline of Antartica in cartopy and this works fine. I can generate a plot with the shapefile and some more information on it. But I'm not able to plot the Longitude and Latitude information at the border of the image.
I use the orthographic projection with central_longitude and central_latitude.
I also need to mention that I'm comparably new to cartopy.
My code:
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader
# 01
b01e01_lat = -73.86750000
b01e01_lon = -60.22694444
b01e02_lat = -73.89166667
b01e02_lon = -56.68500000
b01e03_lat = -74.87222222
b01e03_lon = -58.26805556
b01e04_lat = -74.85000000
b01e04_lon = -60.43083333
b01e05_lat = -73.86750001
b01e05_lon = -60.22694445
b01_lat = np.array([b01e01_lat,b01e02_lat,b01e03_lat,b01e04_lat, b01e01_lat, b01e05_lat])
b01_lon = np.array([b01e01_lon,b01e02_lon,b01e03_lon,b01e04_lon, b01e01_lon, b01e05_lon])
# 02
b02e01_lat = -73.94555556
b02e01_lon = -51.00055556
b02e02_lat = -74.22333333
b02e02_lon = -49.37000000
b02e03_lat = -74.87555556
b02e03_lon = -50.71888889
b02e04_lat = -74.87583333
b02e04_lon = -51.00055556
b02e05_lat = -73.94555557
b02e05_lon = -51.00055557
fname='Coastline_Antarctica_v02.shp'
#ax = plt.axes(projection=ccrs.SouthPolarStereo())
plt.figure()
ax = plt.axes(projection=ccrs.Orthographic(central_longitude=-41,
central_latitude=-71))
ax.set_extent([-85,-12,-75,-60], crs=ccrs.PlateCarree())
ax.add_geometries(Reader(fname).geometries(),ccrs.Orthographic(central_longitude=-0,
central_latitude=-90), color='grey')
ax.gridlines()
plt.plot(b01_lon,b01_lat, color='r', transform=ccrs.PlateCarree())
plt.plot(b02_lon,b02_lat, color='r', transform=ccrs.PlateCarree())
plt.show()
With this I get the following plot (without the blue shapes):
Any help appreciated!
If you run your code to produce interactive plot (using %matplotlib notebook on jupyter notebook), you can move the mouse cursor to read the locations that you need to plot the labels.
With this method, I can get the approximate (long, lat) locations for plotting 2 sample labels. The code to plot them is as follows:
ax.text(-80.6, -57.0, '{0}\N{DEGREE SIGN} S '.format(57), va='center', ha='right',
transform=ccrs.PlateCarree())
ax.text(-75.15, -56.0, '{0}\N{DEGREE SIGN} W '.format(75), va='bottom', ha='center',
transform=ccrs.PlateCarree())
And the output plot will look like this:

Create 3D Plot- Depth/Time/Temp From Large .csv file_Python 3.x

I am trying to create a 3D Temperature plot vs Depth vs Time with a large .csv data-set. The example below is created in matlab. I want a similar output using Python 3.x with reverse scales on the Temperature and Depth axis.
Example output with a few mods needed
I have started off with the following code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# Get the data (csv file is hosted on the web)
data = pd.read_csv('C;\\Path\\TestData_Temp-Time-Depth_3DPlot.csv')
# Transform it to a long format
df = data.unstack().reset_index()
df.columns = ["X", "Y", "Z"]
# And transform the old column name in something numeric
df['X'] = pd.Categorical(df['X'])
df['X'] = df['X'].cat.codes
# Make the plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.jet, linewidth=0.2)
plt.show()
# to Add a color bar which maps values to colors.
surf = ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.jet, linewidth=0.2)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
# Rotate it
ax.view_init(30, 45)
plt.show()
# Other palette
ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.jet, linewidth=0.01)
plt.show()
I am having issues understanding how to assign values from from csv to the x, y, z axis.
The example data I am using is formatted like:
csv data structure
Example data download: Download Example Data
Thank you in advance.

Plotting an Hourly Time Series in the Correct Order with Plotly in Python

I'm trying to plot a timeseries graph and everything is working so far except for the time. For some reason plotly is plotting first days and afterwards it is starting with a different time and for the same period. Normally Plotly should recognise my time format. Does anyone know why it is not working properly?
This is my code:
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
x = ['2017-01-01 00:00:00','2017-01-02 06:00:00','2017-01-03 12:00:00','2017-01-04 18:00:00','2017-01-05 00:00:00',
'2017-01-06 06:00:00','2017-01-07 12:00:00','2017-01-08 18:00:00','2017-01-09 00:00:00','2017-01-10 06:00:00',
'2017-01-01 12:00:00','2017-01-02 18:00:00','2017-01-03 00:00:00','2017-01-04 06:00:00','2017-01-05 12:00:00',
'2017-01-06 18:00:00','2017-01-07 00:00:00','2017-01-08 06:00:00','2017-01-09 12:00:00','2017-01-10 18:00:00',
'2017-01-01 00:00:00','2017-01-02 06:00:00','2017-01-03 12:00:00','2017-01-04 18:00:00','2017-01-05 00:00:00',
'2017-01-06 06:00:00','2017-01-07 12:00:00','2017-01-08 18:00:00','2017-01-09 00:00:00','2017-01-10 06:00:00',
'2017-01-01 12:00:00','2017-01-02 18:00:00','2017-01-03 00:00:00','2017-01-04 06:00:00','2017-01-05 12:00:00',
'2017-01-06 18:00:00','2017-01-07 00:00:00','2017-01-08 06:00:00','2017-01-09 12:00:00','2017-01-10 18:00:00']
y1 = np.random.uniform(low=14, high=19.5, size=(40,))
y2 = np.random.uniform(low=14, high=25.0, size=(40,))
trace1 = go.Scatter(
x=x,
y=y1,
name = "Temperature LED",
line = dict(color = '#17BECF'),
opacity = 0.8)
trace2 = go.Scatter(
x=x,
y=y2,
name = "Temperature MDL",
line = dict(color = '#7F7F7F'),
opacity = 0.8)
data = [trace1,trace2]
layout = dict(
title='Temperature LED vs MDL',
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1,
label='1d',
step='day',
stepmode='backward'),
dict(count=6,
label='6d',
step='day',
stepmode='backward'),
dict(step='all')
])
),
rangeslider=dict(),
type='date'
)
)
fig = dict(data=data, layout=layout)
py.plot(fig, filename="Time Series with Rangeslider")
This is the result:
Plotly does not reorder the x values of your traces before plotting them, and so plotting them out of sequence results in lines that jump back and forth. Sorting your x values (in this case, you can sort in place by just calling x.sort()) before creating your traces fixes the problem:
Note that all of the vertical lines in this plot are the result of all of the times in your x list being included twice (I'm not sure if this was intentional).

Resources