R 如何控制条形图中值标签的小数位数
考虑下图: 这个问题是关于如何将堆叠条中的所有值标签保留在小数点后一位,以保持一致性。因此,将-1、2和5表示为-1.0、2.0和5.0,与其他表示一致。下面是一个示例数据R 如何控制条形图中值标签的小数位数,r,ggplot2,decimal,bar-chart,stacked-chart,R,Ggplot2,Decimal,Bar Chart,Stacked Chart,考虑下图: 这个问题是关于如何将堆叠条中的所有值标签保留在小数点后一位,以保持一致性。因此,将-1、2和5表示为-1.0、2.0和5.0,与其他表示一致。下面是一个示例数据 df <- data.frame(group=c("satisfied", "satisfied", "unsatisfied","unsatisfied", "satisfied", "satisfied",
df <- data.frame(group=c("satisfied", "satisfied",
"unsatisfied","unsatisfied",
"satisfied", "satisfied",
"unsatisfied","unsatisfied"
),
cost=c("low","high","low","high",
"low","high","low","high"),
treatment=c("treated","treated","treated","treated",
"untreated","untreated",
"untreated","untreated") ,
value=c(2.3,8.7,5.0,3.1,9.4,3.1,2.0,-1.0))
进入ggplot函数,但这不会产生所需的输出。我非常感谢您在这方面提供的帮助。问题是您在使用
sprintf
之前进行了四舍五入(并因此转换为字符
,丢失了数字信息)。要格式化数字,您需要给出sprintf
数字,而不是字符串。它将自行处理舍入问题。试试这个:
label = ifelse(value !=0, sprintf("%0.1f", value), "")
制定整个代码:
ggplot(data = df, aes(y = value, x = group, fill = cost)) +
geom_bar(stat = "identity", position = 'stack') +
ylab("Y label") +
theme(
legend.direction = "horizontal",
legend.position = "bottom",
legend.spacing.x = unit(0.1, 'cm')
) +
theme(legend.title = element_blank()) +
geom_text(aes(label = ifelse(value !=0, sprintf("%0.1f", value), "")),
position = position_stack(vjust = 0.5)) +
facet_grid(~ treatment)
由于
ifelse
,上面的内容有点奇怪。一个更标准的ggplot2
解决方案会让您以另一种方式摆脱0-可能在打印前过滤掉它,将data=filter(df,y!=0)
赋予ggplot()
。然后您可以使用缩放
功能
label = scales::label_number(accuracy = 0.1)(value)
将整个代码制作如下,以获得相同的结果:
ggplot(data = dplyr::filter(df, value != 0), aes(y = value, x = group, fill = cost)) +
geom_bar(stat = "identity", position = 'stack') +
ylab("Y label") +
theme(
legend.direction = "horizontal",
legend.position = "bottom",
legend.spacing.x = unit(0.1, 'cm')
) +
theme(legend.title = element_blank()) +
geom_text(aes(label = scales::label_number(accuracy = 0.1)(value)),
position = position_stack(vjust = 0.5)) +
facet_grid(~ treatment)
真正地使用示例数据尝试新的R会话。这对我来说很好。
label = scales::label_number(accuracy = 0.1)(value)
ggplot(data = dplyr::filter(df, value != 0), aes(y = value, x = group, fill = cost)) +
geom_bar(stat = "identity", position = 'stack') +
ylab("Y label") +
theme(
legend.direction = "horizontal",
legend.position = "bottom",
legend.spacing.x = unit(0.1, 'cm')
) +
theme(legend.title = element_blank()) +
geom_text(aes(label = scales::label_number(accuracy = 0.1)(value)),
position = position_stack(vjust = 0.5)) +
facet_grid(~ treatment)