![](/img/trans.png)
[英]How to use ggplot2 to create a graph with multiple y values per x and x values from a vector
[英]How to make a ggplot with one 'x' value and multiple 'y' values
我正在嘗試使用 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()
這導致沒有錯誤,但圖表看起來不正確:失敗的數據表
我還嘗試了更寬的標題:我每個月都有一個帶有 3 個數值的向量,所以每個月都是一列。 不幸的是,我沒有為此保存代碼,但簡而言之,它不起作用。 關於如何組織數據以便繪制數據的任何其他想法?
我認為將數據從寬格式更改為長格式然后繪制它更容易。 三個活動的y
數據相同,因此 Gym 不可見(它被 Yoga 線和點掩蓋)。
library(ggplot2)
library(tidyverse)
self.care <- tibble(Month, Gym, Yoga, Walk)
self.care <- self.care %>% pivot_longer(cols = c(Gym, Yoga, Walk),
names_to = "Activity")
ggplot(self.care,aes(x = Month,
y = value,
col = Activity,
group = Activity)) +
geom_line() +
geom_point() +
#To set x axis labels as vertical
theme(axis.text.x = element_text(angle = 90,
hjust = 1,
vjust = 0.5))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.