Seyma Kalay
Seyma Kalay

Reputation: 2859

ggplot2, unwanted naming in Y-axis

Let's say I have following data:

df <- data.frame(
     "Values" = c("Gender","Gender","Marital Status","Marital Status","Age","Age"),
     "Mean"= c(0.6934877,  0.8536885,  0.8801737,  0.8998975, 54.6858177, 54.1486680),
     "By"= c("Urban", "Rural", "Urban","Rural","Urban", "Rural")
)
df$Values <- factor(df$Values)

levels(df$Values)

df_groupby <- df %>%
      dplyr::group_by(Values) 

Expected results on the y-axis Gender, Marital Status, Age same as in df. Many thanks in advance

I tried that without success

ggplot(df_groupby , aes(Values, Mean)) +
      geom_bar(stat = "identity") +
      coord_flip()

Upvotes: 1

Views: 32

Answers (2)

stefan
stefan

Reputation: 123783

Set the factor levels manually in the wanted order. Then use e.g. forcats::fct_rev to reverse the order in the plot. BTW: df_groupby is not necessary. You can plot using df. Try this:

df <- data.frame(
  "Values" = c("Gender","Gender","Marital Status","Marital Status","Age","Age"),
  "Mean"= c(0.6934877,  0.8536885,  0.8801737,  0.8998975, 54.6858177, 54.1486680),
  "By"= c("Urban", "Rural", "Urban","Rural","Urban", "Rural")
)

library(ggplot2)
library(dplyr)
library(forcats)

df$Values <- factor(df$Values, levels = c("Gender", "Marital Status", "Age"))

levels(df$Values)
#> [1] "Gender"         "Marital Status" "Age"

df_groupby <- df %>%
  dplyr::group_by(Values)

ggplot(df_groupby , aes(forcats::fct_rev(Values), Mean)) +
  geom_bar(stat = "identity") +
  coord_flip()

Created on 2020-04-12 by the reprex package (v0.3.0)

Upvotes: 1

linog
linog

Reputation: 6226

Given your answer to the comment, I slightly modified your workflow to construct the reproducible example.

df <- data.frame(
  "Values" = c("Gender","Gender","Marital Status","Marital Status","Age","Age"),
  "Mean"= c(0.6934877,  0.8536885,  0.8801737,  0.8998975, 54.6858177, 54.1486680),
  "By"= c("Urban", "Rural", "Urban","Rural","Urban", "Rural"),
  stringsAsFactors = FALSE
)
df_groupby <- df %>%
  dplyr::group_by(Values) 

df_groupby$Values <- factor(df_groupby$Values, levels = unique(df$Values), ordered = TRUE) 

If you want categories in the order of your values

ggplot(df_groupby , aes(Values, Mean)) +
  geom_bar(stat = "identity") +
  coord_flip()

enter image description here

If you want them in reverse order

ggplot(df_groupby , aes(Values, Mean)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  scale_y_discrete(limits = rev(levels(df_groupby$Values)))

enter image description here

Upvotes: 1

Related Questions