Reputation: 175
I'm using R's plotly package inside a Shiny Dashboard to create the funnel chart below.
Current plot.
There is a problem with this chart in that the x-axis displays negative values to the left of 0. Normally this wouldn't be a problem of course, but this is a funnel chart, so the values to the left of 0 aren't really negative, because they represent count data. I don't know how to fix it.
Desired plot.
The code is
output$plot_piramide_casos <- renderPlotly({
m <- list(
l = 50,
r = 50,
b = 100,
t = 100,
pad = 4
)
plot_ly(piramide_casos(), x = ~Freq_n, y = ~Faixa, type = 'bar', color = ~Sexo, colors = c("darkorange1", "dodgerblue3"),
text = ~paste("Faixa Etária: ", Faixa, '<br>Número Absoluto:', Freq, '<br>Proporção:', prop,"%"), hoverinfo = 'text') %>%
layout(barmode='relative',
xaxis = list(title = "População", tickformat = "digits", zeroline = FALSE),
yaxis = list(title = "Faixa Etária", zeroline = FALSE)) %>%
layout(title = "Casos confirmados de COVID-19", titlefont = list(size = 24, face="bold"))%>%
layout(autosize = F, width = 545, height = 400, margin = m)
})
Upvotes: 2
Views: 782
Reputation: 39595
You can obtain the same plot combining ggplot2
and plotly
using ggplotly
. I have used some dummy data and dplyr
for transforming variables:
library(ggplot2)
library(plotly)
library(dplyr)
#Data
df <- data.frame(Age=c('0-19','20-29','30-39','40-49','50-69','60-Inf',
'0-19','20-29','30-39','40-49','50-69','60-Inf'),
Pop=c(1000,3000,7000,5000,3000,800,
900,2500,6000,4000,2000,500),
Gender=c(rep('Male',6),rep('Female',6)))
#Code
Plot <- df %>%
mutate(Age=factor(Age,levels = unique(Age),ordered = T),
Pop=ifelse(Gender=='Male',-Pop,Pop)) %>%
ggplot(aes(x=Age,y=Pop,fill=Gender))+
geom_bar(stat = 'identity')+
scale_y_continuous(labels = function(x) abs(x))+
coord_flip()+
scale_fill_manual(values=c('orange','blue'))+
theme_bw()
#Plotly
ggplotly(Plot)
Output:
Upvotes: 2