In my code below (which works just fine) I would like all the fonts when I hover over country on world map to be either bold or non bold. What is happening is as per the following example - say I hover over USA then I get .
562,079 Deaths United States USA
Cases: 30,211,178
Population: 320,635,163
Deaths % by Population:v0.0097%
The "Deaths United Sates" is not bold.
Code
output$World_Map <- renderPlotly({
l <- list(color = toRGB("grey"), width = 0.5)
g <- list(
showframe = FALSE,
showcoastlines = FALSE,
projection = list(type = "kavrayskiy7")
)
fig <- plot_geo(worldmap)
fig <- fig %>% add_trace(
z = ~ worldmap$Deaths,
color = ~ worldmap$Deaths,
colors = 'Reds',
locations = ~ worldmap$Country_Alpha_Code,
marker = list(line = l),
hoverinfo = "text",
text = ~ glue::glue(
"Deaths: {Country.x} <b>{Country_Alpha_Code}<b>\nCases: {comma(Cases,digits=0)}<b>\nPopulation: {comma(Population,digits=0)}<b>\nDeaths % by Population: {comma(Deaths_Perc_Pop,digits=4)}%</b>"
),
hovertemplate = "%{z:,0f}<extra>%{text}</extra>"
)
fig <-
fig %>% colorbar(title = 'Deaths - Positive Cases Gradient', tickformat = ",0f")
fig <-
fig %>% layout(title = 'Covid19 Global Pandemic .... <br>Data Source:Johns Hopkins University of Medicine',
geo = g)
fig
})
Regards
Related
Plotly creates nice maps where the scope term defines the area. I'm wondering if I can make the map so it only shows New York City?
I've read the documentation on scope (https://plotly.com/python/reference/#layout-geo-scope), and see it does not involve any cities, so maybe someone else has a way to solve this?
library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
# geo styling
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showland = TRUE,
landcolor = toRGB("gray95"),
subunitcolor = toRGB("gray85"),
countrycolor = toRGB("gray85"),
countrywidth = 0.5,
subunitwidth = 0.5
)
fig <- plot_geo(df, lat = ~lat, lon = ~long)
fig <- fig %>% add_markers(
text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "<br />"),
color = ~cnt, symbol = I("square"), size = I(8), hoverinfo = "text"
)
fig <- fig %>% colorbar(title = "Incoming flights<br />February 2011")
fig <- fig %>% layout(
title = 'Most trafficked US airports<br />(Hover for airport)', geo = g
)
fig
I am creating a plot with several time series, plotting the mean value and two quantiles in the process and highlighting the region between the quantiles. Then I have a unified hoverinfo showing me all points at one point in time. I do not want this hoverinfo to display the dummy trace that is only there for the highlighting. I tried both hoverinfo = skip and hoverinfo = none, but that only hides any text info, not the trace itself in the hoverinfo.
Here is the code I have (without most "beautification parameters" such as axis width and the likes...):
###creating dummy data
test_data <- data.frame(matrix(0,nrow = 27,ncol = 4))
colnames(test_data) <- c("x","y","value","date")
test_data$x <- c(-1,-1,-1,0,0,0,1,1,1,-1,-1,-1,0,0,0,1,1,1,-1,-1,-1,0,0,0,1,1,1)
test_data$y <- c(-1,0,1,-1,0,1,-1,0,1,-1,0,1,-1,0,1,-1,0,1,-1,0,1,-1,0,1,-1,0,1)
test_data$value <- rnorm(27,mean = 5,sd = 1)
date_vec <- c(rep(as.Date("2022-01-01"),9),rep(as.Date("2022-01-02"),9),rep(as.Date("2022-01-03"),9))
test_data$date <- date_vec
x_levels <- unique(test_data$x)
y_levels <- unique(test_data$y)
avg <- data.frame(matrix(0,nrow = 3,ncol = 1))
colnames(avg) <- c("value")
avg$date <- unique(date_vec)
Q75 <- data.frame(matrix(0,nrow = 3,ncol = 1))
colnames(Q75) <- c("value")
Q75$date <- unique(date_vec)
Q25 <- data.frame(matrix(0,nrow = 3,ncol = 1))
colnames(Q25) <- c("value")
Q25$date <- unique(date_vec)
for (i in 1:length(unique(date_vec))){
avg$value[i] <- mean(test_data$value[test_data$date == unique(date_vec)[i]])
Q75$value[i] <- quantile(test_data$value[test_data$date == unique(date_vec)[i]],0.75)
Q25$value[i] <- quantile(test_data$value[test_data$date == unique(date_vec)[i]],0.25)
}
##creating plot
fig <- plot_ly()
fig <- fig %>% layout(hovermode = 'x unified')
for(i in 1:length(x_levels)){
for(j in 1:length(y_levels)){
fig <- fig %>% add_trace(data = test_data, type = 'scatter', mode = 'lines+markers',
x = test_data$date[test_data$x == x_levels[i] & test_data$y == y_levels[j]],
y = test_data$value[test_data$x == x_levels[i] & test_data$y == y_levels[j]],
showlegend = FALSE, line = list(color = 'grey'), marker = list(color = 'grey'),
hoverinfo = 'text', text = paste0("some text dependent on x and y"))
}}
fig <- fig %>% add_trace(data = Q25, type = 'scatter', mode = 'lines', name = '25%-quantile', x = Q25$date,
y = Q25$value, showlegend = TRUE, line = list(color = 'darkred', dash = 'dot'),
hoverinfo = 'text', text = paste0("some text dependent on Q25"))
fig <- fig %>% add_trace(data = avg, type = 'scatter', mode = 'lines', name = 'mean value', x = avg$date,
y = avg$value, showlegend = TRUE, line = list(color = 'darkred', dahs = 'dash'),
hoverinfo = 'text', text = paste0("some text depenent on avg"))
fig <- fig %>% add_trace(data = Q75, type = 'scatter', mode = 'lines', name = '75%-quantile', x = Q75$date,
y = Q75$value, showlegend = TRUE, line = list(color = 'darkred', dash = 'dot'),
hoverinfo = 'text', text = paste0("some text dependent on Q75"))
#### This is the dummy trace in question:
fig <- fig %>% add_trace(x = Q25$date, y = Q25$value, type = 'scatter', mode = 'lines', fill = 'tonexty',
fillcolor = 'rgba(139,0,0,0.2)', line = list(color = 'darkred', width = 0.1), showlegend = FALSE,
hoverinfo = 'skip')
print(fig)
Is this a bug? Am I missing something obvious? Is there a better way to make the highlighting that does not create an additional hoverinfo? Thanks in advance!
Alright, this answer is not ideal—but it works.
There is good news, though. Plotly developers are already working on a solution. They're in the testing phase, which is where I got the idea for this answer. You can read about what Plotly's doing here.
First, I set a seed because you have random data. I used set.seed(3509). There were no changes to the data or fig.
When you hover over any point on your graph, your fill color will disappear. The tooltip does not show the trace that shouldn't be there anyway.
The fill color will return as soon as you move on or when the tooltip goes away.
This is the Javascript to call this hover event.
# the notation [12] is the curvenumber; it represnts a single trace
hoverer = "function(el, x) {
el.on('plotly_hover', function(d){
dt = {'fill': 'none'};
Plotly.restyle(el.id, dt, [12]);
});
el.on('plotly_unhover', function(d){
ft = {'fill':'tonexty'};
Plotly.restyle(el.id, ft, [12]);
});
}"
To visualize your plot with this event:
fig %>% htmlwidgets::onRender(hoverer)
I want to show the date for every 1 month, but it shows every 2 months instead. I also wonder how to tilt the date (x axis) 60 degree in plotly. Is these two things possible in plotly? Thanks in advance.
My code:
l <- list(
font = list(
family = "sans-serif",
size = 12,
color = "#364E6F"),
bgcolor = "#E4EBF5",
bordercolor = "#566F92",
borderwidth = 3)
fig <- plot_ly(sumir_data, x = sumir_data$`Month-year`, y = sumir_data$`Followers-LI`, type = 'bar', name = 'LinkedIn', marker = list(color = '#28EDC4'))
fig <- fig %>% add_trace(y = sumir_data$`EOM Followers Twitter-TW`, name = 'Twitter', marker = list(color = '#00BBFF'))
fig <- fig %>% layout(yaxis = list(title = 'Followers Count',
color = '#364E6F'))
fig <- fig %>% layout(xaxis = list(title = 'Date',
color = '#364E6F'))
fig <- fig %>% layout(legend = l)
fig <- fig %>% layout(paper_bgcolor = '#E4EBF5',
plot_bgcolor = '#E4EBF5')
fig
The solution would be to add dticks = "M1" to the xaxis layout()
My code:
l <- list(
font = list(
family = "sans-serif",
size = 12,
color = "#364E6F"),
bgcolor = "#FFFFFF",
bordercolor = "#566F92",
borderwidth = 3)
fig <- plot_ly(sumir_data, x = sumir_data$`Month-year`, y = sumir_data$`Followers-LI`, type = 'bar', name = 'LinkedIn', marker = list(color = '#28EDC4'))
fig <- fig %>% add_trace(y = sumir_data$`EOM Followers Twitter-TW`, name = 'Twitter', marker = list(color = '#00BBFF'))
fig <- fig %>% layout(yaxis = list(title = 'Number of Followers',
color = '#364E6F'))
fig <- fig %>% layout(xaxis = list(title = 'Date',
color = '#364E6F', dtick = "M1"))
fig <- fig %>% layout(legend = l)
fig <- fig %>% layout(paper_bgcolor = '#FFFFFF',
plot_bgcolor = '#FFFFFF')
fig
When hovering over a country the numbers are shown as say 125.115k - I want to show it as 125,115
I tried using library(formattable) and something along the lines of z = comma(worldmap$Deaths,digits = 1)
My code is below
output$World_Map <- renderPlotly({
g <- list(
showframe = FALSE,
showcoastlines = FALSE,
projection = list(type = 'Mercator')
)
plot_ly(
worldmap,
type = 'choropleth',
locations = worldmap$COUNTRY_ALPHA_3_CODE,
z = worldmap$Deaths,
text = paste("Number of Deaths: ",worldmap$COUNTRY_SHORT_NAME,"\n",comma(worldmap$Cases, digits = 0),"\n","Number of Cases: ",worldmap$COUNTRY_SHORT_NAME),
colorscale = "Reds"
) %>% layout(title = "<b>Covid19 Global Pandemic .... Data Source: <a href='https://coronavirus.jhu.edu/'>Johns Hopkins University of Medicine</a><b>", geo = g)
})
For comma rendering numbers, I use prettyNum from base R, also comma function is available in scales package.
number_a <- 123456
prettyNum(number_a, big.mark = ",")
[1] "123,456"
Your question is about text tooltip in Plotly. You can do something like this, with hoverinfo/hovertemplate and text parameters.
Of course there are other manners to do it.
Because I don't have your data, I use an example from plotly website.
library(plotly)
# code for example
# https://plotly.com/r/choropleth-maps/#using-builtin-country-and-state-geometries
# doc for hovertemplate
# https://plotly-r.com/controlling-tooltips.html#tooltip-text
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
# light grey boundaries
l <- list(color = toRGB("grey"), width = 0.5)
# specify map projection/options
g <- list(
showframe = FALSE,
showcoastlines = FALSE,
projection = list(type = 'Mercator')
)
fig <- plot_geo(df)
fig <- fig %>% add_trace(
z = ~GDP..BILLIONS., color = ~GDP..BILLIONS., colors = 'Blues',
locations = ~CODE, marker = list(line = l),
hoverinfo = "text",
text = ~glue::glue("{COUNTRY} <b>{CODE}</b>"),
hovertemplate = "%{z:,0f}<extra>%{text}</extra>"
)
fig <- fig %>% colorbar(title = 'GDP Billions US$', tickformat = ",0f")
fig <- fig %>% layout(
title = '2014 Global GDP<br>Source:CIA World Factbook',
geo = g
)
fig
With this you can easily configure your hover info / tooltip.
See here for more examples :
https://plotly.com/r/choropleth-maps/#customize-choropleth-chart
For French number (space instead of comma), you can at the end config locale:
fig %>%
config(locale = 'fr')
I've got three columns of data I would like to plot as a cumulative stacked area chart over a 10 day sampling period.
ID variable value
dallas sample.01 0.0012
austin sample.01 0.23
seattle sample.01 0.01
I'd like it to look something like this:
But it's coming out like this:
What am I doing wrong with my code?
melted_dat %>%
group_by(value,ID) %>%
plot_ly(
x = ~variable,
y = ~value,
color = ~ID,
type='scatter',
mode = 'none',
fill = 'tonexty',
stackgroup = 'one',
fillcolor = ~ID) %>%
layout(showlegend = FALSE)
I think you need to add the groups trace by trace. As in the following example (from here):
library(plotly)
data <- t(USPersonalExpenditure)
data <- data.frame("year"=rownames(data), data)
p <- plot_ly(data, x = ~year, y = ~Food.and.Tobacco, name = 'Food and Tobacco', type = 'scatter', mode = 'none', stackgroup = 'one', groupnorm = 'percent', fillcolor = '#F5FF8D') %>%
add_trace(y = ~Household.Operation, name = 'Household Operation', fillcolor = '#50CB86') %>%
add_trace(y = ~Medical.and.Health, name = 'Medical and Health', fillcolor = '#4C74C9') %>%
add_trace(y = ~Personal.Care, name = 'Personal Care', fillcolor = '#700961') %>%
add_trace(y = ~Private.Education, name = 'Private Education', fillcolor = '#312F44') %>%
layout(title = 'United States Personal Expenditures by Categories',
xaxis = list(title = "",
showgrid = FALSE),
yaxis = list(title = "Proportion from the Total Expenditures",
showgrid = FALSE,
ticksuffix = '%'))
# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = api_create(p, filename="area-stackedcum")
chart_link
If you are following the cumulative example from plotly, don't do the group_by .... cumsum, I also get rid of fillcolor