Reputation: 88
I have made a plot in plotly with the following code:
Geocode <- c("Onondaga County", "Oswego County", "Cayuga County")
nclients <- c(2237,540,502)
n_txt <- c("2237","540","502")
df <- data.frame(Geocode,nclients,n_txt)
df %>% plot_ly() %>%
add_trace(x = ~Geocode,
y=~nclients,
color=~Geocode,
text=~n_txt,
textposition="outside",
textfont=list(color='#000000'),
type='bar',
hovertemplate = "%{y} clients were %{x} ",
marker = list(line=list(color='rgb(8,48,107)',width=1.5))) %>%
layout(title="Whole year count by county",
barmode='group',
xaxis = list(title=""),
yaxis = list(title=""))
There are 2 things I want to change here:
Thanks for any help you can provide!
Upvotes: 1
Views: 1113
Reputation: 4344
hi a fast solution would be to work it with the text variable directly that solves two issues:
library(dplyr)
library(ggplot2)
library(plotly)
df <- data.frame(Geocode = c("Onondaga County", "Oswego County", "Cayuga County"),
nclients = c(2237,540,502),
n_txt = c("aaa","ddd","ccc"))
df %>% plot_ly() %>%
add_trace(x =~Geocode,
y=~nclients,
color=~Geocode,
textposition="none", # change this to get fixed labels on the bars ie. top
textfont=list(color='#000000'),
type='bar',
text = ~list(paste('n_txt:', n_txt,
'<br>Geocode:',Geocode,
'<br>nclients',nclients)),
hoverinfo = 'text',
marker = list(line=list(color='rgb(8,48,107)',width=1.5))) %>%
layout(title="Whole year count by county",
barmode='group',
xaxis = list(title=""),
yaxis = list(title=""))
If you opt for texposition above the whole text gets on top of the bar though. Inside the hover template the secondary label can be removed - about the text label I am not sure how to solve it but we can put the text on top of the bars (or omit it ie.):
df %>%
plot_ly() %>%
add_trace(x = ~Geocode,
y=~nclients,
color=~Geocode,
text=~n_txt,
textfont=list(color='#000000'),
type='bar',
textposition="outside",
hovertemplate = paste("%{y} clients were",
"%{x}",
"<extra></extra>"), # this removes the secondary label
marker = list(line=list(color='rgb(8,48,107)',width=1.5))) %>%
layout(title="Whole year count by county",
barmode='group',
xaxis = list(title=""),
yaxis = list(title=""))
I tried something with this info (section "Advanced Hovertemplate" but it somehow does not work reliably (no idea why): https://plotly.com/r/hover-text-and-formatting/
Upvotes: 4