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

时间:2019-02-22 19:16:08

标签: 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"))

输出Bar graph

我研究过进行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).

1 个答案:

答案 0 :(得分:5)

您的问题是,通过格式化percents$percent列,您会将它们保存为因素

> class(percents$percent)
[1] "factor"

快速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"))

但是,我建议您不要更改数据框中的格式,而应将格式保留为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)