无法通过使用ggplot2从excel工作表调用来获得变量的绘图和逐日日期

问题描述 投票:0回答:1

我正在尝试为两个变量绘制geom_col,这是我从Excel工作表中调用的。数据采用时间序列格式。

这是我的数据集。我想在一个栏中为所有日期同时绘制变量'Johor'和'TCK'。

head(df2)
# A tibble: 6 x 33
  date       Johor   TCJ Kedah  TCKe Kelantan TCKlntn Melaka  TCMk N.Sembilan  TCN9 Pahang
  <date>     <dbl> <dbl> <dbl> <dbl>    <dbl>   <dbl>  <dbl> <dbl>      <dbl> <dbl>  <dbl>
1 2020-01-25     1     1     0     0        0       0      0     0          0     0      0
2 2020-01-26     0     1     0     0        0       0      0     0          0     0      0
3 2020-01-27     0     1     0     0        0       0      0     0          0     0      0
4 2020-01-28     1     2     1     1        0       0      0     0          0     0      0
5 2020-01-29     0     2     0     1        0       0      0     0          0     0      0
6 2020-01-30     1     3     0     1        0       0      0     0          0     0      0

这是我的ggplot2代码

ggplot(df2,aes(x=date, y=Johor, col=c(TCJ+Johor), group=c(TCJ+Johor)))+ 
  geom_col(aes(fill=c(TCJ+Johor)),width=0.5
  )+
  theme(axis.text.x = element_text(angle=15, vjust=0.4)) +
  labs(title="",
       subtitle="")

我也想在x实验室中拥有所有日期,但对我来说我只能有一个月enter image description here

必需的绘图输出。

My expectation plot should be like as follows

ggplot2 rstudio
1个回答
0
投票

关于堆积的条形图:

看来您需要将数据集以长格式放置(并在TCJ和Johor的过滤器之后:]

library("tidyverse")     
df2 %>%
      pivot_longer(-date, names_to = "name", values_to = "value") %>%
      filter(name %in% c("Johor", "TCJ")) %>%
      ggplot(aes(date, value, fill = name)) +
      geom_col(position = "stack")
© www.soinside.com 2019 - 2024. All rights reserved.