I created the below graph, but I want the labels on the y axis to show in logical order : "Less than $20,000", "$20,000 to $34,999", "$35,000 to $49,999", "$50,000 to $74,999", "$75,000 to $99,999", "Over $100,000" as opposed to the way it is ordered on the graph. I used the following code to create the graph:
ggplot(dat2)
aes(x = trust, y = income, shape = own, color = own)
geom_jitter()
scale_color_discrete(name= "Home Ownership",
labels=c('Other', 'I Own My Home'))
scale_shape_discrete(name = "Home Ownership",
breaks=c("0", "1"), labels=c('Other', 'I Own My Home'))
How can I reorder the labels on the y axis?
I have tried to reorder the factor but that only returned a data of all .
dat2$income <- factor(x = dat2$income, levels = c("Less than $20,000", "$20,000 to $34,999", "$35,000 to $49,999", "$50,000 to $74,999", "$75,000 to $99,999", "Over [enter image description here][1]$100,000"))
I have also tried to use scale_y_discrete(limits = c("Less than $20,000", "$20,000 to $34,999", "$35,000 to $49,999", "$50,000 to $74,999", "$75,000 to $99,999", "Over $100,000"))
inside the ggplot function but that returned a blank graph with and error message:
"Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
3: Removed 498 rows containing missing values (geom_point).
4: Position guide is perpendicular to the intended axis. Did you mean to specify a different guide position
?
CodePudding user response:
You can reorder the factor before plotting:
dat2$income <- factor(x = dat2$income,
levels = c("Less than $20,000", "$20,000 to $34,999",
"$35,000 to $49,999", "$50,000 to $74,999",
"$75,000 to $99,999", "Over $100,000"))
ggplot(dat2)
aes(x = trust, y = income, shape = own, color = own)
...
# ------------------------- Update ------------------------- #
# Without factor reorder
df1 <- data.frame(a = c("Less than $20,000", "$20,000 to $34,999",
"$35,000 to $49,999", "$50,000 to $74,999",
"$75,000 to $99,999", "Over $100,000"),
b = 1:6)
ggplot(df1, aes(a, b))
geom_bar(stat = 'identity')
theme(axis.text.x.bottom = element_text(angle = 30, vjust = 0.7))
# With factor reorder
df2 <- data.frame(a = c("Less than $20,000", "$20,000 to $34,999",
"$35,000 to $49,999", "$50,000 to $74,999",
"$75,000 to $99,999", "Over $100,000"),
b = 1:6)
df2$a <- factor(df2$a,
levels = c("Less than $20,000", "$20,000 to $34,999",
"$35,000 to $49,999", "$50,000 to $74,999",
"$75,000 to $99,999", "Over $100,000"))
ggplot(df2, aes(a, b))
geom_bar(stat = 'identity')
theme(axis.text.x.bottom = element_text(angle = 30, vjust = 0.7))