使用R/ggplot2将标签添加到geom_bar()内的单个%
我如何获得单个百分比的标签?更具体地说,我希望每个酒吧有4个单独的百分比。黄色、浅橙色、橙色和红色各一个。%'s全部加起来等于1使用R/ggplot2将标签添加到geom_bar()内的单个%,r,ggplot2,R,Ggplot2,我如何获得单个百分比的标签?更具体地说,我希望每个酒吧有4个单独的百分比。黄色、浅橙色、橙色和红色各一个。%'s全部加起来等于1 创建一个在位置内具有相对频率的摘要框架,然后将其与geom\u col()和geom\u text()一起使用,怎么样 #创建摘要统计数据 总计% 分组依据(位置、成功)%>% 总结( n=n() ) %>% 变异( rel=四舍五入(100*n/和(n)), ) #密谋 ggplot(数据=tots,aes(x=位置,y=n))+ geom_col(aes(fill
创建一个在
位置内具有相对频率的摘要框架,然后将其与geom\u col()
和geom\u text()一起使用,怎么样
#创建摘要统计数据
总计%
分组依据(位置、成功)%>%
总结(
n=n()
) %>%
变异(
rel=四舍五入(100*n/和(n)),
)
#密谋
ggplot(数据=tots,aes(x=位置,y=n))+
geom_col(aes(fill=fct_rev(success))+#只能通过此方法获得它
geom_文本(aes(标签=rel),位置=position_堆栈(vjust=0.5))
输出:
创建一个在位置内具有相对频率的摘要框架,然后将其与geom\u col()
和geom\u text()一起使用,怎么样
#创建摘要统计数据
总计%
分组依据(位置、成功)%>%
总结(
n=n()
) %>%
变异(
rel=四舍五入(100*n/和(n)),
)
#密谋
ggplot(数据=tots,aes(x=位置,y=n))+
geom_col(aes(fill=fct_rev(success))+#只能通过此方法获得它
geom_文本(aes(标签=rel),位置=position_堆栈(vjust=0.5))
输出:
也许有一种方法可以直接在ggplot
中执行此操作,但是通过dplyr
中的一些预处理,您将能够实现所需的输出
# Create summary stats
tots <-
data %>%
group_by(location,success) %>%
summarise(
n = n()
) %>%
mutate(
rel = round(100*n/sum(n)),
)
# Plot
ggplot(data = tots, aes(x = location, y = n)) +
geom_col(aes(fill = fct_rev(success))) + # could only get it with this reversed
geom_text(aes(label = rel), position = position_stack(vjust = 0.5))
也许有一种方法可以直接在ggplot
中执行此操作,但是通过dplyr
中的一些预处理,您将能够实现所需的输出
# Create summary stats
tots <-
data %>%
group_by(location,success) %>%
summarise(
n = n()
) %>%
mutate(
rel = round(100*n/sum(n)),
)
# Plot
ggplot(data = tots, aes(x = location, y = n)) +
geom_col(aes(fill = fct_rev(success))) + # could only get it with this reversed
geom_text(aes(label = rel), position = position_stack(vjust = 0.5))
请提供您的数据样本,以使此问题重复性。我可能不理解您的目的,但position='fill'
是否会做到这一点<代码>几何图形栏(aes(fill=success),位置='fill')
@AHart,否,将图表调整为100%的图表区域。我的目标是让百分比标签悬停在每个单条的相应颜色上。请包含一个数据样本,以使这个问题重现。我可能不明白你在追求什么,但position='fill'
会做这个把戏吗<代码>几何图形栏(aes(fill=success),位置='fill')
@AHart,否,将图表调整为100%的图表区域。我的目标是让百分比标签悬停在每个单条的相应颜色上。谢谢Ronak,这是完美的谢谢Ronak,这是完美的
# Create summary stats
tots <-
data %>%
group_by(location,success) %>%
summarise(
n = n()
) %>%
mutate(
rel = round(100*n/sum(n)),
)
# Plot
ggplot(data = tots, aes(x = location, y = n)) +
geom_col(aes(fill = fct_rev(success))) + # could only get it with this reversed
geom_text(aes(label = rel), position = position_stack(vjust = 0.5))
library(dplyr)
library(ggplot2)
data %>%
count(location, success) %>%
group_by(location) %>%
mutate(n = n/sum(n) * 100) %>%
ggplot() + aes(x = location, n, fill = success,label = paste0(round(n, 2), "%")) +
geom_bar(stat = "identity") +
geom_text(position=position_stack(vjust=0.5))