Stuck on How to Display Hover Data in Specific Format - python

I am testing some plotly code here.
import plotly.express as px
# find business profits
pd.options.display.float_format = '{:.2f}'.format
df_gains = df_rev_exp[((df_rev_exp.ltd_spending) < df_rev_exp.REV2)]
df_gains.tail()
# scatter plot of losses
import plotly.express as px
fig = px.scatter(df_gains, x="site_name",
y="gain_or_loss",
color="gain_or_loss",
size='REV2', hover_data=['site_name','REV2'])
fig.update_xaxes(tickangle=325)
fig.show()
Everything plots just fine but the REV2 is pretty large, and as such it is hard to read when I hover over the data points in the chart. I'm trying to figure out a way to show numbers as millions. For instance, In would like to see 1.25M and not 1257789.84, which is what I am seeing now. I tried playing around with fig.update but I couldn't get anything working. How can I modify the formatting on these plotly charts?

I'm on Plotly 4.14.3 and this version shows 2.2M straight out of the box when the source is x=[10000000, 22000000, 34000000]:
import numpy as np
import plotly.graph_objects as go
fig = go.Figure()
fig.add_traces(go.Scatter(x=[10*10**6, 22*10**6, 34*10**6],
y=[10,12,14]))
fig.show()
So two things come to mind:
Update Plotly.
Check that you're inputting your values as values and not strings

Related

Is there a way to plot lines over a datashader plot in Bokeh (Python)?

I am working with relatively large datasets (approximately 10x20.000.000 data point), for which Datashader is a useful visualisation tool. To give more information in these visualisations, I would like to add lines showing averages/standarddeviations on top of this datashade figure. Does anyone know how this would be possible?
My current code:
from bokeh.plotting import figure
from bokeh.io import show
x = 'xcol'
y= 'ycol'
data = dataframe
fig = figure(x_axis_label=x, y_axis_label=y)
points = hv.Points(data[[x, y]], label=('Title'))
hd.datashade(points, cmap='crest')
What I would like to do is for example add the following line to the figure generated with the code above:
fig.line([1,10,20], [0, 1000,2000], line_width=4)
Thanks in advance.

How to plot addresses (Lat/Long) from a csv on JSON map.?

So I am trying to do something which seems relatively simple but is proving incredibly difficult. I have a .csv file with addresses and their correspondent latitude/longitude, I just want to plot those on a California JSON map like this one in python:
https://github.com/deldersveld/topojson/blob/master/countries/us-states/CA-06-california-counties.json
I've tried bubble maps, scatter maps, etc. but to no luck I keep getting all kind of errors :(. This is the closest I've got, but that uses a world map and can't zoom in effectively like that json map up there. I am still learning python so please go easy on me ><
import plotly.express as px
import pandas as pd
df = pd.read_csv(r"C:\Users\FT4\Desktop\FT Imported Data\Calimapdata.csv")
fig = px.scatter_geo(df,lat='Latitude',lon='Longitude', hover_name="lic_type", scope="usa")
fig.update_layout(title = 'World map', title_x=0.5)
fig.show()
If anyone could help me with this I would appreciate it. Thank you
your example link is just a GeoJSON geometry definition. Are you talking about a Choropleth?
If so, check out geopandas - you should be able to link your data to the polygons in the shape definition you linked to by reading it in with geojson and then joining on the shapes with sjoin. Once you have data tied to each geometry, you can plot with geopandas's .plot method. Check out the user guide for more info.
Something along these lines should work:
import geopandas as gpd, pandas as pd
geojson_raw_url = (
"https://raw.githubusercontent.com/deldersveld/topojson/"
"master/countries/us-states/CA-06-california-counties.json"
)
gdf = gpd.read_file(geojson_raw_url, engine="GeoJSON")
df = pd.read_csv(r"C:\Users\FT4\Desktop\FT Imported Data\Calimapdata.csv")
merged = gpd.sjoin(gdf, df, how='right')
# you could plot this directly with geopandas
merged.plot("lic_type")
alternatively, using #r-beginners' excellent answer to another question, we can plot with express:
fig = px.choropleth(merged, geojson=merged.geometry, locations=merged.index, color="lic_type")
fig.update_geos(fitbounds="locations", visible=False)
fig.show()

Create subplots with plotly using a loop

Is there a way to create a subplot with Plotly Express using a for to plot the data? I've tried some things here but nothing worked as expected. This is my last try:
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=int(len(unique_pds)/2), cols=2)
for pds in unique_pds:
fig.add_trace(
go.Histogram(x=df[(df['Resolved'] >= resolved_date) &
(df['Components'].astype(str).str.contains(components)) &
(df['planned_effort'] == pds)]['lead_time']
)
).show()
The solution works almost perfectly, but the problem is that it is generating various subplots separated. I need all of them to be under the same subplot.
Thanks for the help.
Marcelo

Plotly Express choropleth map not showing in visual studio code

Below shown the syntax used to get a map visualized and plotted from Plotly Express - choropleth from a "csv" DataFrame.
import pandas as pd
import numpy as np
import plotly.express as px
df = "//location.csv"
fig = px.choropleth(data_frame = df,
locations= df["location"],
locationmode='country names',
color=df["location"],
hover_name=df["location"],
title = "Location Data",
color_continuous_scale = px.colors.sequential.Oranges)
fig["layout"].pop("updatemenus")
fig.show()
However, when I use the above syntax on the Visual Studio Code Jupyter Notebook, the map does not get visualized and plotted. Which is shown as below,
But when I run the same code on the Anaconda Jupyter Notebook, I do get the map visualized and plotted as shown below,
Why isn't the map not getting visualized and plotted on VS code, and is there any way to resolve this issue on VS code?
I was interested in this question because I usually work with jypyterLab. I ran it based on this answer, and when I ran it in vscode, it displayed correctly in my default browser. The code I ran was based on the code in the official reference.
import plotly.express as px
from plotly.offline import plot
df = px.data.gapminder().query("year==2007")
fig = px.choropleth(df, locations="iso_alpha",
color="lifeExp", # lifeExp is a column of gapminder
hover_name="country", # column to add to hover information
color_continuous_scale=px.colors.sequential.Plasma)
# fig.show()
plot(fig)

How to disable a line in plotly at start?

I would like to show the lines but with some are disabled. So just like when I show it normally and then click on its name to unshow/disable the line.
I am using python.
visible attribute of a trace as "legendonly" makes a line behave in way you describe
Below code generates a figure with 10 lines, then sets visible to legendonly for lines 3 to 10. Clicking on legend makes them visible.
import pandas as pd
import numpy as np
import plotly.express as px
df = pd.DataFrame({f"line{i+1}":np.random.uniform(i,i+2,100) for i in range(10)})
px.line(df, x=df.index, y=df.columns).update_traces(visible="legendonly", selector=lambda t: not t.name in ["line1","line2"])

Categories

Resources