我正在创建一个堆叠条形图。数据中的年份被重新编码成组,这些组用于绘制图表。我的图表颜色与图例颜色不匹配,我不明白为什么。图例是正确的,图表上的注解数据值也是正确的,这些数据条以正确的顺序显示,但颜色相反。
的数据
library(dplyr);
library(tidyverse);
library(ggplot2);
# Define UI for application that draws a histogram
ui <- fluidPage(
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
thepast <- paste0(as.character(as.integer(format(Sys.Date(), "%Y"))-2),"-")
lastyear <- as.character(as.integer(format(Sys.Date(), "%Y"))-1)
thisyear <- as.character(as.integer(format(Sys.Date(), "%Y")))
nextyear <- as.character(as.integer(format(Sys.Date(), "%Y"))+1)
nextyear2 <- as.character(as.integer(format(Sys.Date(), "%Y"))+2)
future <- paste0(as.character(as.integer(format(Sys.Date(), "%Y"))+3),"+")
bardata <- data.frame(BAR_CHOICES = c('None',thepast,lastyear,thisyear,nextyear),
total_count=c(1530,300,156,393,272)) %>%
mutate(
BAR_CHOICES = factor(
BAR_CHOICES ,
levels=c( 'None', thepast,lastyear, thisyear, nextyear, nextyear2, future )
)
) %>%
arrange(
factor(
BAR_CHOICES ,
levels=c( 'None', thepast,lastyear, thisyear, nextyear, nextyear2, future )
)
)
output$distPlot <- renderPlot({
ggplot(
bardata ,
aes(x = NA, y = total_count, fill = rev(BAR_CHOICES), label = total_count)) +
geom_col() +
scale_fill_manual(values = setNames(c('black','#6f7171','#ff8027','#ffe97a','#006fc1','#dcf5e6','#008331'),c('None', thepast,lastyear, thisyear, nextyear,nextyear2,future))) +
geom_text(position = position_stack(vjust = 0.5), size = 4.5, color = "black", fontface="bold") +
guides(fill = guide_legend(reverse=FALSE , nrow=2)) +
coord_flip() +
scale_x_discrete(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
theme(axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.position="bottom",
legend.title=element_blank() ,
legend.text=element_text(size=12),
panel.background=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
plot.background=element_blank()) +
ggtitle("Estimated Solution Completion")
}, height=150)
}
# Run the application
shinyApp(ui = ui, server = server)
字符串
1条答案
按热度按时间sd2nnvve1#
问题是您将
rev(BAR_CHOICES)
Map到fill
上。这样您就恢复了BAR_CHOICES
列的顺序,并且将类别分配给了错误的计数。通过在ggplot()
之外执行此步骤可以清楚地看到:字符串
相反,如果你想颠倒
BAR_CHOICES
的顺序,那么在转换为factor()
时颠倒级别的顺序,或者使用forcats::fct_rev()
或position_stack(reverse=TRUE)
颠倒堆栈的顺序:型
的数据