【问题标题】:ggplot : How to use column names as x-axis label and the values as y-axisggplot:如何使用列名作为 x 轴标签和值作为 y 轴
【发布时间】:2021-05-05 09:11:27
【问题描述】:

找不到解决此问题的方法!

我想绘制一个包含 4 列的数据框,如下所示:

Species Mean for today Mean RCP26 Mean RCP85
1 0.567 0.765 0.342
2 0.987 0.543 0.001
3 0.456 0.876 0.54

现在我想将 col 名称绘制为 x 轴标签以及它们上方的相应值。物种应该在图例中有一个颜色代码。最后希望能得到一张线图,展示从今天到rcp85的发展历程。

我正在尝试使用 ggplot 几个小时,但我找不到实现它的方法。很高兴能得到一些帮助。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

您需要先旋转您的数据,这是通过 gather 实现的,您还需要 group 美学来获得一条带有离散 x 轴的线

require(dplyr)
require(ggplot2)
    
df %>% 
gather(var, val , -Species) %>% 
ggplot(aes(x = var, y = val, color = as.factor(Species), group = as.factor(Species)))+
geom_line() 

【讨论】:

  • gather() 的开发已经完成,对于新代码,我们建议切换到 pivot_longer()。 tidyr.tidyverse.org/reference/gather.html>
【解决方案2】:

我还使用tidyr 旋转表格。

library(ggplot2)
library(dplyr)
library(tidyr)

df %>% 
  pivot_longer(cols = 2:4, names_to = "indicators", values_to = "values") %>% 
  ggplot(data = ., aes(x = indicators, y = values, color = as.factor(Species), group = Species)) +
    geom_point()

输出:

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多