【发布时间】:2020-01-11 00:28:39
【问题描述】:
我正在尝试使用 ggplot 创建线/点图,但我很难弄清楚如何在一个图形上创建 3 条单独的线。我希望图表对于每种类型的活动(健身房、瑜伽、步行)都有 1 条线,x 轴是月份,y 轴是天数。
这是我的数据:
>### Self-care Tracker ###
>
> library(tidyverse)
>
> Month <- c("January", "February", "March", "April", "May", "June", "July",
+ "August", "September", "October", "November", "December")
>
> Gym <- c(3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
> Yoga <- c(2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
> Walk <- c(3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
>
>
> self.care <- tibble(Month, Gym, Yoga, Walk)
> self.care
# A tibble: 12 x 4
Month Gym Yoga Walk
<chr> <dbl> <dbl> <dbl>
1 January 3 2 3
2 February 1 1 1
3 March 1 1 1
4 April 1 1 1
5 May 1 1 1
6 June 1 1 1
7 July 1 1 1
8 August 1 1 1
9 September 1 1 1
10 October 1 1 1
11 November 1 1 1
12 December 1 1 1
这是一次绘图尝试:
> ggplot() +
+ geom_line(self.care, aes(x = Month, y = Gym)) +
+ geom_line(self.care, aes(x = Month, y = Yoga)) +
+ geom_line(self.care, aes(x = Month, y = Walk))
Error: `mapping` must be created by `aes()'
我也尝试将数据放入 ggplot 的参数中,如下所示:
ggplot(self.care, aes(x = Month, y = c(Gym, Yoga, Walk)) +
geom_point() + geom_line()
这没有导致错误,但图表看起来不正确: Failed Data Table
我还尝试了更宽的 tibble:我每个月都有一个包含 3 个数值的向量,所以每个月都是一列。不幸的是,我没有为此保存代码,但简而言之,它没有用。 关于如何组织数据以便绘制数据的任何其他想法?
【问题讨论】:
-
你很接近。
geom_line的第一个参数是审美,这就是你得到错误的原因。将self.care作为数据参数提供给ggplot,并将美学传递给geom_line。