如何为条形图转换y轴(ggplot2)

时间:2017-10-16 07:48:11

标签: r ggplot2

示例数据test

   a b       c
1  a x      NA
2  b x 5.1e-03
3  c x 2.0e-01
4  d x 6.7e-05
5  e x 5.1e-03
6  f y 6.2e-05
7  g y 1.0e-02
8  h y 2.5e-03
9  i y 9.8e-02
10 j y 8.7e-04

说我想用这组数据绘制条形图。但由于这些值彼此相差几个数量级,因此难以明显地将图形可视化。如何改变y轴,使其值为0,10 -6 ,10 -5 ,10 -4 ...... 10 -1

到目前为止,我一直在尝试使用ggplot,但我无法让它发挥作用。谢谢!

ggplot(test,
       aes(fill=a,
           y=c,
           x=b)) + 
  geom_bar(position="dodge",
           stat="identity")+
  coord_trans(y="log10")

dput(test) :(我不知道这种情况的相关性,但无论如何都是这样。)

structure(list(a = structure(1:10, .Label = c("a", "b", "c", 
"d", "e", "f", "g", "h", "i", "j"), class = "factor"), b = structure(c(1L, 
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("x", "y"), class = "factor"), 
c = c(NA, 0.0051, 0.2, 6.7e-05, 0.0051, 6.2e-05, 0.01, 0.0025, 
0.098, 0.00087)), .Names = c("a", "b", "c"), row.names = c(NA, 
-10L), class = "data.frame")

1 个答案:

答案 0 :(得分:3)

要使用log10比例和反向条,我在-log(c, 10)中使用了aes()。为了在y轴上使用科学记数法,我使用了科学格式的scale_y_continous

library(ggplot2)
ggplot(test, aes(b, -log(c, 10), fill = a)) +
    geom_bar(stat = "identity", position = "dodge") +
    scale_y_continuous(labels = function(x) format(x, scientific = TRUE))

enter image description here

您可以使用labs(y = "")将y轴重命名为您想要的任何内容,例如:labs(y = "-log10 C")

相关问题