我的目标是在ggplot中创建带有百分比标签的堆叠条形图。经过研究并阅读了一些材料后,我设法管理了所需的图表。有很多材料。
R堆叠百分比条形图,带有二进制因子和标签的百分比(带ggplot)
但是,我有两个问题:
1)我找不到合适的放置标签的地方。您会看到标签未居中且位于错误的部分。(图生成时未使用闪亮) 如何解决此问题?
第二个问题是当我尝试在中使用绘图代码时shiny
。我使用以下功能创建标签:df$label = paste0(sprintf("%.0f", df$percent), "%")
,但是插入标签时reactive
出现错误。在实际情况下,我有更困难的数据生成和子集示例,因此我的数据必须为reactive
。
另外,我附上了该应用程序的可重现esample。
我的目标是绘制漂亮labels
的stacked percent bar chart
在ggplot
。
library(shiny)
library(shinydashboard)
library(plyr)
library(ggplot2)
# Header -----------------------------------------------------------
header <- dashboardHeader(title= "DashBoard")
# Sidebar --------------------------------------------------------------
sm <- sidebarMenu(
menuItem(
text="stacked bar chart",
tabName="chart",
icon=icon("eye")
)
)
sidebar <- dashboardSidebar(sm)
# Body --------------------------------------------------
body <- dashboardBody(
# Layout --------------------------------------------
tabItems(
tabItem(
tabName="chart",
fluidPage(
fluidRow(
title = "Inputs", status = "warning", width = 2, solidHeader = TRUE, collapsible = TRUE,
plotOutput("M1"),
dataTableOutput(outputId="M3")
)
)
)
)
)
# Setup Shiny app UI components -------------------------------------------
ui <- dashboardPage(header, sidebar, body)
# Setup Shiny app back-end components -------------------------------------
server <- function(input, output) {
# -----------------------------------------------------------------------------
#reproducable data generation
Mdata <- reactive({
set.seed(1992)
n=8
Category <- sample(c("Car", "Bus", "Bike"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL))
USD <- abs(rnorm(n))*100
df <- data.frame(Category, Brand, USD)
# Calculate the percentages
df = ddply(df, .(Brand), transform, percent = USD/sum(USD) * 100)
# Format the labels and calculate their positions
df = ddply(df, .(Brand), transform, pos = (cumsum(USD) - 0.5 * USD))
#create nice labes
#df$label = paste0(sprintf("%.0f", df$percent), "%")
})
output$M1 <- renderPlot({
ggplot(Mdata(), aes(x=reorder(Brand,USD,
function(x)+sum(x)), y=percent, fill=Category))+
geom_bar(position = "fill", stat='identity', width = .7)+
geom_text(aes(label=percent, ymax=100, ymin=0), vjust=0, hjust=2, color = "white", position=position_fill())+
coord_flip()+
scale_y_continuous(labels = percent_format())+
ylab("")+
xlab("")
})
output$M3 <- renderDataTable({
Mdata()
})
# -----------------------------------------------------------------------------
}
# Render Shiny app --------------------------------------------------------
shinyApp(ui, server)
来自paste0
命令的错误是因为它是中的最后一行reactive
,因此成为返回值。只需添加一条语句return(df)
或等效的内容即可解决该问题。
至于标签的位置,代码按设计工作,您必须计算所需的位置geom_text
并明确使用这些坐标,这需要您汇总每个品牌段的坐标,以便知道其左右位置并可以计算中心
其他答案可以在这里找到:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句