【问题标题】:How to show the count in legend as percent in geom_hex plot如何在 geom_hex 图中将图例中的计数显示为百分比
【发布时间】:2020-03-15 07:41:06
【问题描述】:

在下面的情节中:

我想将图例中的计数更改为百分比而不是计数。为了生成情节,我编写了以下脚本:

  library("RColorBrewer")
  df <- read.csv("/home/adam/Desktop/data_norm.csv")
  d <- ggplot(df, aes(case1, case2)) + geom_hex(bins = 30) + theme_bw() +
    theme(text = element_text(face = "bold", size = 16)) + xlab("Case 2") + ylab("Case 1") 
  d <- d + scale_fill_gradientn(colors = brewer.pal(3,"Dark2"))

使用dput 函数生成可重现的示例:

structure(list(ID = c(14L, 15L, 38L, 6L, 7L, 1L, 32L, 31L, 
17L, 30L, 19L, 24L, 5L, 5L, 7L, 8L, 35L, 4L, 1L, 6L, 45L, 58L, 
59L, 5L, 11L, 29L, 6L, 7L, 22L, 23L, 3L, 4L, 25L, 3L, 20L, 16L, 
21L, 109L, 108L, 54L, 111L, 105L, 114L, 28L, 27L, 2L, 24L, 26L, 
50L, 49L, 51L, 48L, 56L, 54L, 53L, 55L, 57L, 52L, 25L, 22L, 34L, 
23L, 19L, 38L, 39L, 18L, 13L, 27L, 11L), case1 = c(2L, 0L, 
0L, 0L, 4L, 17L, 11L, 7L, 9L, 11L, 14L, 5L, 1L, 0L, 0L, 0L, 1L, 
0L, 0L, 0L, 0L, 0L, 0L, 26L, 0L, 16L, 0L, 0L, 6L, 4L, 1L, 10L, 
3L, 13L, 13L, 12L, 6L, 0L, 0L, 11L, 0L, 0L, 0L, 0L, 3L, 16L, 
4L, 3L, 0L, 0L, 0L, 11L, 0L, 0L, 0L, 0L, 0L, 8L, 5L, 7L, 8L, 
7L, 4L, 0L, 1L, 15L, 2L, 19L, 2L), case2 = c(30L, 0L, 0L, 
0L, 30L, 30L, 29L, 29L, 29L, 29L, 29L, 29L, 30L, 30L, 30L, 30L, 
30L, 30L, 30L, 30L, 0L, 29L, 25L, 30L, 30L, 29L, 0L, 0L, 29L, 
29L, 30L, 30L, 30L, 30L, 29L, 29L, 29L, 0L, 3L, 29L, 16L, 14L, 
0L, 30L, 30L, 30L, 30L, 30L, 30L, 30L, 30L, 30L, 23L, 29L, 30L, 
30L, 30L, 30L, 30L, 30L, 30L, 30L, 29L, 0L, 30L, 29L, 30L, 29L, 
30L)), class = "data.frame", row.names = c(NA, -69L))

如何在脚本中进行更改,以便以百分比形式显示计数,而不是显示确切的计数?

【问题讨论】:

  • @divibisan 但这是我不想改变的 y 轴。我只想将图例计数显示为百分比。
  • @divibisan 我更新了问题并添加了一个可重现的示例。

标签: r ggplot2


【解决方案1】:

要更改刻度标签的显示方式而不更改基础值,您可以将重新格式化函数传递给任何 scale_* 函数的 labels= 参数:

plot <- ggplot(df, aes(case1, case2)) + geom_hex(bins = 30) +
            theme_bw() +
            theme(text = element_text(face = "bold", size = 16)) +
            xlab("Case 2") +
            ylab("Case 1")

要将案例数量转换为总案例的百分比,我们只需将每个值除以 df 中的案例总数:

plot + scale_fill_gradientn(colors = brewer.pal(3,"Dark2"),
                            labels = function(x) x/nrow(df))

How can I change the Y-axis figures into percentages in a barplot? 的答案提供了多种将它们转换为适当百分比的方法,但最简单的方法是使用来自scales 包(包含在ggplot2 中)的percent

plot + scale_fill_gradientn(colors = brewer.pal(3,"Dark2"),
                            labels = function(x) scales::percent(x/nrow(df)))

如果您想指定breaks 以便刻度列出特定的舍入百分比,请注意列出的中断需要引用原始值,而不是转换后的百分比。您可以通过反转您在labels 中使用的任何转换来做到这一点:

plot + scale_fill_gradientn(colors = brewer.pal(3,"Dark2"),
                            labels = function(x) scales::percent(x/nrow(df)),
                            breaks = c(.05, .1, .15, .2, .25, .3) * nrow(df))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多