如何更改条形图y轴以表示其值?

tws*_*ewx 2 r ggplot2

我希望只绘制落在频段内的测量百分比.我将它们分为低中和高中.但是当我绘制它们时,它将代表性地显示不显示值(参见图像,例如输出)

代码如下

percents <- data.frame(TI = c("Low","Med","High"),
                   percent = c(format((totallowcount/totalvaluescount)*100,digits=3),
                             format((totalmedcount/totalvaluescount)*100,digits=3),
                             format((totalhighcount/totalvaluescount)*100,digits=3)))

TIbarplot <- ggplot(data = percents, aes(x = TI, y = percent)) + 
  geom_bar(stat = 'identity') + 
  scale_x_discrete(limits = c("Low","Med","High"))
Run Code Online (Sandbox Code Playgroud)

产量条状图.

我查看了做scale_y_discrete,scale_y_discrete(limits=c(0,25,50,100))但一直在为它获取错误.

Error in matrix(value, n, p) : 'data' must be of a vector type, was 'NULL' In addition: Warning message: Removed 3 rows containing missing values (position_stack).

Dav*_*ald 5

您的问题是通过格式化percents$percent列,您将这些保存为因子

> class(percents$percent)
[1] "factor"
Run Code Online (Sandbox Code Playgroud)

快速dplyr::mutate可以更改类ggplot

library(dplyr)
percents %>% 
  mutate(percent = as.numeric(as.character(percent))) %>% 
  ggplot(aes(x = TI, y = percent)) + 
  geom_bar(stat = 'identity') + 
  scale_x_discrete(limits = c("Low","Med","High"))
Run Code Online (Sandbox Code Playgroud)

但是,我建议您不要更改数据框中的格式,并将格式保留为ggplot功能:

percents <- data.frame(TI = c("Low","Med","High"),
                       percent = c(totallowcount/totalvaluescount,
                                   totalmedcount/totalvaluescount,
                                   totalhighcount/totalvaluescount))

ggplot(data = percents, aes(x = TI, y = percent)) + 
  geom_bar(stat = 'identity') + 
  scale_x_discrete(limits = c("Low","Med","High")) +
  scale_y_continuous(labels = scales::percent)
Run Code Online (Sandbox Code Playgroud)