【问题标题】:R - Named numeric vectors and ggplot2 bar chartR - 命名数字向量和 ggplot2 条形图
【发布时间】:2017-09-20 15:09:36
【问题描述】:

我正在尝试使用 ggplot2 制作条形图 - 但遇到了问题。

本质上,我想生成一个水平条形图,其中:

  • Y 轴上的地理位置;

  • 沿 x 轴的人口计数。

但是,我有一个具有以下结构的数据框:

       data.frame(Park = c("Northumberland","South Downs","Dartmoor"), 
       count = c(22.5,24.4,26.0))

正如预期的那样,人口计数直接绘制在 x 轴上,而我希望它绘制在 y 轴上。

有什么想法吗?

对不起,这是一个简单的问题。

【问题讨论】:

  • 如果您分享了您尝试过但不起作用的 ggplot 代码,将会有所帮助。 (在您的问题中,而不是在评论中。)

标签: r plot ggplot2


【解决方案1】:

coord_flip 交换 x 和 y 轴。

library(ggplot2)
dat <- data.frame(Park = c("Northumberland","South Downs","Dartmoor"), 
                  count = c(22.5,24.4,26.0))

ggplot(dat, aes(x=Park, weight=count)) + geom_bar() + coord_flip()

【讨论】:

    【解决方案2】:

    你可以使用geom_col:

    df = data.frame(Park = c("Northumberland","South Downs","Dartmoor"), 
               count = c(22.5,24.4,26.0))
    
    library(ggplot2)
    ggplot(df, aes(x = Park, y = count)) +
      geom_col()
    

    要使用geom_bar,您需要指定stat = "identity" 才能提供y 变量:

    library(ggplot2)
    ggplot(df, aes(x = Park, y = count)) +
      geom_bar(stat = "identity") +
      coord_flip()
    

    【讨论】:

    • 嗨,为了清楚起见,我在上面添加了一张照片。可以肯定的是,我希望 x 轴是通用比例,y 轴是地理位置的值,但刻度线表示位置的名称。
    猜你喜欢
    • 2021-03-14
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2016-06-29
    • 1970-01-01
    相关资源
    最近更新 更多