I am trying to change the symbol from circle to location pin to highlight the co-ordinates on to the map.However, apart from "circle" no other options work correctly in the symbol option.
I have tried - square,marker, triangle.Can someone tell me how to fix this, it doesnt throw an error
#Plotting co-ordinates on to the map
fig = go.Figure(go.Scattermapbox
(
lat=df["Latitude"],
lon=df["Longitude"],
mode='markers',
marker=go.scattermapbox.Marker
(
size=10,
color = df['Size'],
colorscale = 'RdYlGn_r',
showscale=True,
symbol = 'star'
)
)
Please note that markers different from "circle" (default) work only if you are using "vector tiles from the Mapbox service" (e.g. "dark" or "satellite") for which your mapbox token needs to be provided; but they don't work if you are using "open" vector tiles" like "open-street-map"
In the plotly documentation they do this using another syntax, have you tried that already?
import plotly.graph_objects as go
token = open(".mapbox_token").read() # you need your own token
fig = go.Figure(go.Scattermapbox(
mode = "markers+text+lines",
lon = [-75, -80, -50], lat = [45, 20, -20],
marker = {'size': 20, 'symbol': ["bus", "harbor", "airport"]},
text = ["Bus", "Harbor", "airport"],textposition = "bottom right"))
fig.update_layout(
mapbox = {
'accesstoken': token,
'style': "outdoors", 'zoom': 0.7},
showlegend = False)
fig.show()
Source: https://plot.ly/python/scattermapbox/#set-marker-symbols
Apparently it's impossible to set both a non-circle symbol and a marker color at once.
Note that the array marker.color and marker.size are only available
for “circle” symbols.
Source: https://plotly.com/python-api-reference/generated/plotly.graph_objects.Scattermapbox.html
Related
I'm new in using plotly and I'm trying to make a 2 different graph and show them individually through button; however, when I make it, the legends duplicated, resulting to a bad visualization of the data. Here's the code that I'm running right now:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import plotly as ply
import plotly.express as px
import plotly.graph_objects as go
url = "https://raw.githubusercontent.com/m23chaffee/DS100-Repository/main/Aluminum%20Alloy%20Data%20Set.csv"
alloy = pd.read_csv('https://raw.githubusercontent.com/m23chaffee/DS100-Repository/main/Aluminum%20Alloy%20Data%20Set.csv')
del alloy['temper']
alloy = alloy.rename(columns={'aluminum_alloy':'Alloy Number',
'modulus_elastic': 'Elastic Modulus',
'modulus_shear': 'Shear Modulus',
'strength_yield': 'Yield Strength',
'strength_tensile': 'Tensile Strength'
})
bar1 = px.bar(alloy,
x = "Alloy Number",
y = ["Elastic Modulus", "Shear Modulus","Yield Strength","Tensile Strength"],
barmode = 'group',
width = 1100,
height =500,
orientation = 'v',
color_discrete_sequence = px.colors.qualitative.Pastel,
labels={"value": "Data Values"},
template = 'seaborn').update_traces(legendgroup="group").update_layout(showlegend=False)
line1 = px.line(alloy,
x = "Alloy Number",
y = ["Elastic Modulus", "Shear Modulus","Yield Strength","Tensile Strength"],
width = 1100,
height =500,
orientation = 'v',
color_discrete_sequence = px.colors.qualitative.Pastel,
labels={"value": "Data Values"},
template = 'seaborn').update_traces(legendgroup="group", visible = 'legendonly').update_layout(showlegend=False)
# Add buttom
fig.update_layout(
updatemenus=[
dict(
type = "buttons",
direction = "left",
buttons=list([
dict(
args=['type', 'bar'],
label="Bar Graph",
method="restyle",
),
dict(
args=["type", "line"],
label="Line Graph",
method="restyle"
)
]),
pad={"r": 10, "t": 10},
showactive=True,
x=0.11,
xanchor="left",
y=1.1,
yanchor="middle"
),
]
)
fig.show()
and the result of the image would look like this:
Result of the code above
Attempted Solution
I tried to hide it using traces and in the documentation but it seems it didn't work out for me. I also found a similar stackoverflow post 8 years ago, tried it, and it didn't make any changes in my graph.
I want to add text on the lines added using Polyline from within the folium library.(etc "1km" or "1ft")
m = folium.Map(location=[41.08468198029149, 28.8180159802915])
points = [[41.0370023, 28.9850917], [40.98186700000001, 29.0576302]]
for point in points:
folium.Marker(point).add_to(m)
folium.PolyLine(points, color="red", weight=2.5, opacity=1).add_to(m)
Something like that
[EDIT]
I find it!
Check it out
line = folium.PolyLine(points, color="red", weight=2.5, opacity=1)
attr = {'fill': '#007DEF', 'font-weight': 'bold', 'font-size': '24'}
wind_textpath = plugins.PolyLineTextPath(line,
"20 km",
center=True,
offset=7,
attributes=attr)
m.add_child(line)
m.add_child(wind_textpath)
I have tried to add title to colorbar but not able to see on plot.
Code:
fig = go.Figure(go.Scatter(
x=df['Date'],
y = df["GC1"],
mode='markers',
# showlegend = True,
hovertext=df['MM_ln'],
hoverlabel=dict(namelength=0),
hovertemplate='%{hovertext}<br>Date: %{x} <br>MM_l: %{y}',
marker=dict(
size=df["GC1"]*0.01,
color=df["MM_l_cc"], #set color to MM_l_cc
colorscale='Viridis', # one of plotly colorscales
showscale=True,
)
))
# fig.layout.coloraxis.colorbar.title = 'Title'
fig.update_layout(
title='Positioning price concentration MM_l',
xaxis_title='Weekly observations',
yaxis_title='Gold price',
meta=dict(colorbar=dict(title="Title"))
)
# fig.layout.coloraxis.colorbar.title = 'another title'
fig.show()
Ouput:
Where is the mistake? How to solve this? Can anyone please suggest?
You can include it in go.Scatter() like so
import plotly.graph_objects as go
fig = go.Figure(data=go.Scatter(colorbar={"title": "Your title"},
z=[[1, 20, 30],
[20, 1, 60],
[30, 60, 1]]))
fig.show()
or you can include it in the layout update like so
fig.update_layout(
coloraxis_colorbar=dict(
title="Your Title",
),
)
I was able to see the title, after adding colorbar inside marker in my code as
marker=dict(
...
colorbar={"title": "Your title"},
)
I have written the following code to heat heatmap of US-States. But I am unable to get the output image in Google Colab.
State codes are two alphabet codes for a particular state of the US.
temp = pd.DataFrame(project_data.groupby("school_state")["project_is_approved"].apply(np.mean)).reset_index()
temp.columns = ['state_code', 'num_proposals']
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = temp['state_code'],
z = temp['num_proposals'].astype(float),
locationmode = 'USA-states',
text = temp['state_code'],
marker = dict(line = dict (color = 'rgb(255,255,255)',width = 2)),
colorbar = dict(title = "% of pro")
) ]
layout = dict(
title = 'Project Proposals % of Acceptance Rate by US States',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
offline.iplot(fig, filename='us-map-heat-map')
I have imported following libraries:
from chart_studio import plotly
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()
from collections import Counter
import chart_studio.plotly as py
Try the following code with your data:
(I tried putting your variables in the correct spots)
choropleth = go.Choropleth(
locations=temp['state_code'],
locationmode='USA-states',
z = temp['num_proposals'].astype(float),
zmin = 0,
zmax = max(temp['num_proposals'].astype(float)),
colorscale=scl,
autocolorscale=False,
text='Proposals',
marker_line_color='white',
colorbar_title="% Acceptance Rate"
)
fig = go.Figure(data=choropleth)
fig.update_layout(
title_text='Project Proposals % of Acceptance Rate by US States',
geo = dict(
scope='usa',
projection=go.layout.geo.Projection(type = 'albers usa'),
showlakes=True,
lakecolor='rgb(255, 255, 255)'),
)
fig.show()
This code works by creating the Plotly Choropleth Graph Object with your data, then loading that object into a Plotly Figure Graph Object, then updating the layout (for proper titles and zooms), and finally displaying the figure.
I'm trying to create slider that as you drag the slider, the portion of the graph that is shown is only what is on the slider. For example, if you look at my graph below, if the slider was set to 1990, you would only see the lines from 1990 to 2016. I found a working example with plotly but I wanted to see if it could be done with Bokeh.
This is my code so far:
p = figure(width = 900, height = 450)
p.xaxis.axis_label = 'Year'
p.yaxis.axis_label = 'Aggregated Number of Degrees in Education'
source = ColumnDataSource(df)
fill_source = ColumnDataSource(data=dict(x=[],y=[]))
# Create objects for each line that will be plotted
stem = p.line('year', 'stem', line_color='#8dd3c7', line_width=3, source=source)
stem = p.circle('year', 'stem', line_color='#8dd3c7', line_width=3, source=source)
sped = p.line('year', 'sped', line_color='#fdb462', line_width=3, source=source)
elem = p.line('year', 'elem', line_color='#bebada', line_width=3, source=source)
elem = p.square('year', 'elem', line_color='#bebada', line_width=3, source=source)
other = p.line('year', 'other', line_color='#fb8072', line_width=4, source=source)
aggtotal = p.line('year', 'aggtotal', line_dash=[4,4,], line_color='#80b1d3', line_width=3, source=source)
yaxis = p.select(dict(type=Axis, layout="left"))[0]
yaxis.formatter.use_scientific = False
legend = Legend(items=[("STEM", [stem])
,("SPED" , [sped])
,("Elementary", [elem])
,("Other", [other])
,("Total Education Graduates", [aggtotal])], location=(0, 0))
p.add_tools(HoverTool(tooltips=[("Date", "#year")]))
p.add_layout(legend, 'right')
callback_test = CustomJS(args=dict(source=source,fill_source=fill_source), code="""
var data = source.data;
var fill_data = fill_source.data;
var s_val = cb_obj.value;
fill_data['x']=[];
fill_data['y']=[];
for (i = 0; i < s_val; i++) {
fill_data['y'][i].push(data['y'][i]);
fill_data['x'][i].push(data['x'][i]);
}
fill_source.trigger('change');
""")
sped_slider = Slider(start=1984, end= 2016, value=1, step=1,title="Year",callback=callback_test)
callback_test.args["sped"] = sped_slider
layout = row(p,widgetbox(sped_slider))
This renders a slider but it doesn't do anything and I'm not sure where to go from here.
There are some issues with your callback code. For example:
you loop i from 0 to s_val (which may be 1990) which is not consistent with the length of your arrays.
your glyphs references columns 'stem', etc... but the fill_source has columns 'x' and 'y'
your glyphs reference source as a source but you change and trigger event on fill_source.
All that could probably be fixed but there's a much easier way, adjust the range in the callback. E.g. replace your callback by this:
x_range = p.x_range
callback_test = CustomJS(args=dict(x_range=x_range), code="""
var start = cb_obj.value;
x_range.start = start;
x_range.change.emit();
""")
Note the change to the event trigger. Your version would work but I think it's going to be deprecated.
Also:
this line callback_test.args["sped"] = sped_slider is not necessary
you could add toolbar_location='above' in figure(...) to avoid rendering conflict with the legend
you're still going to have a layout problem between the slider and the legend which can be fixed in different ways (slider under or put the slider and the legend in a column before adding to the right of the plot, etc...)