RJ34
RJ34

Reputation: 29

want to plot stacked or different facets showing each of the column

In the R program, I want to plot a stacked bar plot or plot with facets showing as many as the number of the columns.

for the stacked bar plot, I have this data in excel, given in Table 1:

Table 1

Code is below to plot stacked bar:

x3<- read.xlsx("D:\\R\\phenology.xlsx", sheet = 1)
x1=x3$Years
print(x1)
df <-data.frame(Years  = x3$Years,
            PI = x3$`Panicle.initiation.days.(Days)`,
            AD= x3$`Anthesis.days.(Days)`,
            MD = x3$`Maturity.days.(Days)`)
print(df)
Phenology <-data.frame(PI = x3$`Panicle.initiation.days.(Days)`,
            AD= x3$`Anthesis.days.(Days)`,
            MD = x3$`Maturity.days.(Days)`)
print(Phenology)
ggplot(data = df, aes(x= Years, y = Phenology)) + 
geom_bar(stat='identity', col = "green")

***For various facets with number of columns I am using this code":

ggplot(data = df, aes(x= Years, y = Phenology,fill = PI & AD & MD)) 
+geom_bar() + facet_grid(~PI & AD & MD)

It would be helpful if I could get suggestions to resolve the issue on these two codes in R.

Upvotes: 1

Views: 55

Answers (1)

TarJae
TarJae

Reputation: 78937

Update:

First and important bring your data in long format! This is important due to different reasons and not scope of this question:

You do this with pivot_longer. If you do not determine names_to and values_to you will get name and value as default column name.

https://tidyr.tidyverse.org/reference/pivot_longer.html

you could for example do

df %>% 
  pivot_longer(
   -Years # the column not to reshaped
   names_to = "my desired column name", 
   values_to = "my desired value name"
  )...
library(tidyverse)

df %>% 
  pivot_longer(
    -Years
  ) %>% 
  ggplot(aes(x=factor(Years), y=value, fill=name))+
  geom_col()

enter image description here

Upvotes: 1

Related Questions