[英]Fixing X-axis of Horizontal Plotly Bar Chart
I'm using R's plotly package inside a Shiny Dashboard to create the funnel chart below.我在 Shiny 仪表板中使用 R 的plotly package 来创建下面的漏斗图。
Current plot.当前 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.这个图表有一个问题,就是 x 轴在 0 的左边显示负值。通常这当然不是问题,但这是一个漏斗图,所以 0 左边的值不是t 真的是负数,因为它们代表计数数据。 I don't know how to fix it.
我不知道如何解决它。
Desired plot.所需的 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)
})
You can obtain the same plot combining ggplot2
and plotly
using ggplotly
.您可以使用 ggplotly 组合
ggplot2
和plotly
获得相同的ggplotly
。 I have used some dummy data and dplyr
for transforming variables:我使用了一些虚拟数据和
dplyr
来转换变量:
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: Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.