I have a Scatter chart and I need to trace the bisector line on it. I'm wondering if there is a automated way on Plotly to generate that, or a simplified way to calculate the equation in python to generate the list of values and trace the line.
My code:
trace1 = go.Scatter(
x = eixo_x, # My list of values for 'x'
y = eixo_y, # My list of values for 'y'
mode = 'markers',
marker = dict(color = 'rgb(0, 176, 240)')
)
dados = [trace1]
layout = go.Layout(
title = 'Unitários Observados | Unitários Estimados',
autosize = False,
width = 1000,
height = 500,
xaxis = dict(
showgrid = True),
yaxis = dict(
tickmode = 'array',
showgrid = True
)
)
fig = go.Figure(data = dados, layout = layout)
fig.show()
My Plot:
Now I need to plot a line on diagonal, the bisector.
EDIT
There are a few questions about bisector, but not for Plotly.
EDIT 2
In geometry, bisection is the division of something into two equal or congruent parts, usually by a line, which is then called a bisector. Wikipedia
Example:
I didn't use an equation or an automated function from Plotly but the following code solved my problem temporarily:
I've setted the line limits for x and y getting the min and max from each list:
# Trace 2
line_x = [min(eixo_x), max(eixo_x)]
line_y = [min(eixo_y), max(eixo_y)]
And added a second trace for it:
trace2 = go.Scatter(
x = line_x,
y = line_y,
mode = 'lines',
marker = dict(color = 'rgb(127, 127, 127)'),
line = dict(dash = 'dash')
)
Result:
Related
This question already has answers here:
Plotly: How to make a figure with multiple lines and shaded area for standard deviations?
(4 answers)
Closed 1 year ago.
I need to plot data with continuous error bands. I would like to use Plotly Express in the same way as plotly.express.scatter, but instead of error bars to get continuous error bands. With "continuous error bands" I am talking about this:
I wrote the following function to extend plotly.express.line with the same high level interface of Plotly Express. In case it is useful to other people, this is the function:
import plotly.express as px
import plotly.graph_objs as go
def line(error_y_mode=None, **kwargs):
"""Extension of `plotly.express.line` to use error bands."""
ERROR_MODES = {'bar','band','bars','bands',None}
if error_y_mode not in ERROR_MODES:
raise ValueError(f"'error_y_mode' must be one of {ERROR_MODES}, received {repr(error_y_mode)}.")
if error_y_mode in {'bar','bars',None}:
fig = px.line(**kwargs)
elif error_y_mode in {'band','bands'}:
if 'error_y' not in kwargs:
raise ValueError(f"If you provide argument 'error_y_mode' you must also provide 'error_y'.")
figure_with_error_bars = px.line(**kwargs)
fig = px.line(**{arg: val for arg,val in kwargs.items() if arg != 'error_y'})
for data in figure_with_error_bars.data:
x = list(data['x'])
y_upper = list(data['y'] + data['error_y']['array'])
y_lower = list(data['y'] - data['error_y']['array'] if data['error_y']['arrayminus'] is None else data['y'] - data['error_y']['arrayminus'])
color = f"rgba({tuple(int(data['line']['color'].lstrip('#')[i:i+2], 16) for i in (0, 2, 4))},.3)".replace('((','(').replace('),',',').replace(' ','')
fig.add_trace(
go.Scatter(
x = x+x[::-1],
y = y_upper+y_lower[::-1],
fill = 'toself',
fillcolor = color,
line = dict(
color = 'rgba(255,255,255,0)'
),
hoverinfo = "skip",
showlegend = False,
legendgroup = data['legendgroup'],
xaxis = data['xaxis'],
yaxis = data['yaxis'],
)
)
# Reorder data as said here: https://stackoverflow.com/a/66854398/8849755
reordered_data = []
for i in range(int(len(fig.data)/2)):
reordered_data.append(fig.data[i+int(len(fig.data)/2)])
reordered_data.append(fig.data[i])
fig.data = tuple(reordered_data)
return fig
and this is an usage example:
import plotly.express as px
import pandas
df = px.data.gapminder().query('continent=="Americas"')
df = df[df['country'].isin({'Argentina','Brazil','Colombia'})]
df['lifeExp std'] = df['lifeExp']*.1 # Invent some error data...
for error_y_mode in {'band', 'bar'}:
fig = line(
data_frame = df,
x = 'year',
y = 'lifeExp',
error_y = 'lifeExp std',
error_y_mode = error_y_mode,
color = 'country',
title = f'Using error {error_y_mode}',
markers = '.',
)
fig.show()
which should produce the following two plots:
I am trying to format my Plotly Bar Chart x-axis to percentages with 3 decimal points.
import chart_studio.plotly as py #for plotting
import plotly.graph_objs as go
y = ['niner', 'deuce', 'checker']
x = [0.03, -0.05, 0.075]
fig = go.Figure(go.Bar(y = y, x = x,
name = 'returns',
orientation = 'h',
marker = dict(color = '#003663',
line = dict(
color = '#afafaf',
width = 1.5)
)))
fig.update_layout(
title = 'Why So Hard Plotly?',
xaxis = dict(
tickformat = '%.format.%3f',
title = 'Returns',
fixedrange = True,
hoverformat = '.3f',
showgrid = True),
yaxis = dict(
fixedrange = True,
hoverformat = '.3f',
showgrid = True,
),
bargap = 0.2,
barmode = 'relative',
)
fig.update_yaxes(automargin=True)
fig.show()
I can get the y-axis to appear as a rounded percentage using tickformat = '%',
but I can't get more decimals to appears. The Plotly d3 documentation isn't clear (to me) how to do this. Any help is appreciated.
Thanks in advance.
I believe that setting tickformat to ".3%" should do it. Formatting 0.512345 this way yields 51.235%.
I'm trying to plot a polar chart with python and plotly to show the orientation of fibers in an 2D image (see the code below).
It would be great if you could show me how to change the angular axis, currently ranging from 0° to 360°, to match my data ranging from -90° to 90°.
Below are example images of a half polar chart, the format of my data, and my code.
import plotly.graph_objs as go
from plotly import plotly
import plotly.offline as offline
import numpy as np
# data
x= np.genfromtxt(see data image)
y= np.genfromtxt(see data image)
trace = [
go.Scatterpolar(
r = [y], #radial coordinates
theta = [x], #angular coordinates
mode = 'markers',
marker = dict(
color = 'peru'
)
)
]
layout = go.Layout(
showlegend = True,
polar = dict(
domain = dict( # set chart size and position
x = [0, 0.8],
y = [0.3, 0.8]),
sector = [0, 180], # set chart shape (half or full)
angularaxis = dict(
thetaunit = "degrees",
dtick = 10),
radialaxis = dict(
range = [1, 8000])
))
fig = go.Figure(data=trace, layout=layout)
offline.plot(fig)
x-y data
half polar chart for fiber orientation
Thank you very much DatHydroGuy! I completely rewrote the code with your changes and it is working now. Below is the code and an image of the output. NOICE! Thanks again, HydroGuy, for you help!
If somebody knows how to rotate it (by 90° counterclockwise) and mirror it (-90 left, 0 top, 90 right) please let me know. I tried rotation= and direction= commands, but they did not work and collide with the sector= command for setting the angular axis range from -90 to 90.
Cheers, Ron
import plotly.graph_objs as go
from plotly import plotly
import plotly.offline as offline
import numpy as np
import plotly
# data
x= np.genfromtxt("data.csv", delimiter=",", usecols=(0), skip_header=1, encoding = 'unicode_escape')
y= np.genfromtxt("data.csv", delimiter=",", usecols=(1), skip_header=1, encoding = 'unicode_escape')
trace = [
go.Scatterpolar(
r = [float(a) for a in y], #radial coordinates
theta = [float(b) for b in x], #angular coordinates
mode = 'lines',
marker = dict(
color = 'peru'
)
)
]
layout = go.Layout(
showlegend = True,
legend=dict(
x=1),
polar = dict(
domain = dict( # set chart size and position
x = [0, 1],
y = [0, 1]),
sector = [-90,90], # set chart shape (half or full)
angularaxis = dict(
thetaunit = "degrees",
dtick = 10,
#rotation = -90, #does not work
#direction = "clockwise" # does not work
),
radialaxis = dict(
range = [1, 6500])
))
fig = go.Figure(data=trace, layout=layout)
offline.plot(fig)
plotly half polar plot
OK, so I only got output by making the following changes:
Changed the go.Layout sector=[0, 180] to sector=[-90, 90]
Changed the go.Scatterplot r=[y] to r=[float(a) for a in y]
Changed the go.Scatterplot theta=[x] to theta=[float(b) for b in x]
The first change created the range that you require (-90 to 90)
The 2nd and 3rd changes converted the results from np.genfromtext() from strings to numeric (although these changes may not be necessary if your data is already numerical within x and y).
My code now looks like this:
import plotly.graph_objs as go
import plotly.offline as offline
import numpy as np
# data
x = np.genfromtxt([str(i) for i in range(-90, 91)])
y = np.genfromtxt([str(i * 25 + np.random.randint(1000, 2500)) for i in range(0, 181)])
trace = [
go.Scatterpolar(
r=[float(a) for a in y], # radial coordinates
theta=[float(b) for b in x], # angular coordinates
thetaunit="degrees",
mode='markers',
marker=dict(
color='peru'
)
)
]
layout = go.Layout(
showlegend=True,
polar=dict(
domain=dict( # set chart size and position
x=[0, 0.8],
y=[0.3, 0.8]),
sector=[0, 1800], # set chart shape (half or full)
angularaxis=dict(
thetaunit="degrees",
dtick=10,
rotation=90,
direction='clockwise'),
radialaxis=dict(
range=[1, 8000])
)
)
fig = go.Figure(data=trace, layout=layout)
offline.plot(fig)
These changes were sufficient to produce the following:
Is that what you are looking for?
I am having an issue with graph resizing due to legends when using pyplot. This is the code:
random_x = df['column1']
random_y = df['column2']
random_x1 = df['column1']
random_y1 = df['column3']
trace = go.Scatter(
x = random_x,
y = random_y,
name='abcdefghijklmnop......'
)
trace1 = go.Scatter(
x = random_x1,
y = random_y1,
name='abcdefghijklmnopadfdsfsdff......'
)
data = [trace,trace1]
iplot(data, filename='basic-line')
It gives me the graph but since my legend characters are long, it reduces the size of my actual graph. I want the legends to either come at the bottom or go further to the top
layout = go.Layout(
legend=dict(
orientation="h")
)
figure=go.Figure(data=data, layout=layout)
iplot(figure,filename='basic-line')
I'm plotting some data similar to the first example found here (the US airports map). However, rather than plotting a scale I'm plotting binary features (let's say one color is over 15k flights and one color is under 15k flights). I've looked at the documentation but can't find a way to do a legend if I wanted to do this sort of plot. Does anyone know how?
You could specify the color according to your condition, e.g.
color = np.where(df['Set'] > 15000, 'red', 'green')
but then you wouldn't have a nice legend.
An alternative approach would be to add two plots, one for each condition.
import pandas as pd
import plotly
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
data = dict(
type = 'scattergeo',
locationmode = 'USA-states',
mode = 'markers'
)
data_high = data.copy()
data_high['lon'] = df[df['cnt'] > 10000 ]['long']
data_high['lat'] = df[df['cnt'] > 10000 ]['lat']
data_high['marker'] = dict(color = 'red')
data_high['name'] = '> 10000'
data_low = data.copy()
data_low['lon'] = df[df['cnt'] <= 10000 ]['long']
data_low['lat'] = df[df['cnt'] <= 10000 ]['lat']
data_low['marker'] = dict(color = 'green')
data_low['name'] = '<= 10000'
layout = dict(
geo = dict(
scope = 'usa',
projection = dict(type='albers usa'),
),
)
fig = dict(data=[data_high, data_low], layout=layout)
plotly.offline.plot(fig)