简体   繁体   English

如何在 R 中使用 plot 分类模式?

[英]How can I plot categorical pattern in R?

Year        Dist        Ratio
<int>       <chr>       <dbl>
2018        A       1.576287
2018        B       3.487632
2018        C       2.827363
2019        A       2.176387
2019        B       1.326874
2019        C       1.728745

ggplot(data = df) +
  geom_line(aes(x = Year, y = Ratio)) 

but it shown但它显示

在此处输入图像描述

How can I plot similar pattern to the picture?我怎样才能让 plot 与图片相似?

Are you after this?你在追求这个吗?

ggplot(data = df) +
  geom_line(aes(x = Year, y = Ratio, color = Dist))

在此处输入图像描述


Or following @Konrad Rudolph' comment, we can convert Year into date type, eg,或者按照@Konrad Rudolph 的评论,我们可以将Year转换为date类型,例如,

ggplot(data = df) +
  geom_line(aes(x = as.Date(paste0(Year,"-01-01")), y = Ratio, group = Dist))

You can use this code:您可以使用以下代码:

library(tibble)
library(ggplot2)
df <- tribble(
~Year,        ~Dist,        ~Ratio,
2018, "A", 1.576287, 
2018, "B", 3.487632, 
2018, "C", 2.827363, 
2019, "A", 2.176387, 
2019, "B", 1.326874, 
2019, "C", 1.728745)

df$Year <- as.factor(df$Year)
df$Dist <- as.factor(df$Dist)
ggplot(data = df) +
  geom_line(aes(x = Dist, y = Ratio, colour = Year, group = Year)) +
  theme_classic()

在此处输入图像描述

In the linked image, the x-axis is categorical , and is so because the variable passed in aes(x =...) is a character vector or factor vector.在链接图像中,x 轴是categorical ,之所以如此,是因为传入aes(x =...)的变量是字符向量或因子向量。

In your case, Year is numerical, hence the x-axis is interpreted as a nominal scale, as you can have 2018, 2018.9, 2018.999, 2019.0, 2020 (never mind that it doesn't necessarily makes sense in your case).在您的情况下, Year是数字,因此 x 轴被解释为标称比例,因为您可以有 2018、2018.9、2018.999、2019.0、2020(没关系,这在您的情况下不一定有意义)。

To force the x-axis, convert the Year -variable into a factor, as such:要强制 x 轴,请将Year变量转换为一个因子,如下所示:

ggplot(data = df) +
  geom_line(aes(x = as.factor(Year), y = Ratio)) +
  labs(x="Year")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM