2
set.seed(357)
x <- data.frame(name = sample(letters, 10), val = runif(10), stringsAsFactors = F)
x[c(2,6),"name"] <- c("k","k")
ggplot(x, aes(x = name, y = val)) + theme_bw() + geom_bar(stat = "identity")

How can I plot the axis in the same order as x$name? (Yes, the k is duplicate, I want that to show up in the plot like this axis: c k g f o k s v t q)

In the past I used to do:

x$name <- factor(x$name, levels = x$name[order(x$val)], ordered = T)

wich doesn't work any more thanks to: http://r.789695.n4.nabble.com/factors-with-non-unique-quot-duplicated-quot-levels-have-been-deprecated-since-2009-are-more-depreca-td4721481.html

This is no duplicate of: ggplot: order of factors with duplicate levels His data structure is completely different.

Also, I have tried setting limits in x_scale_discrete. Doesn't work.

Community
  • 1
  • 1
user5878028
  • 117
  • 1
  • 13

2 Answers2

4

Try this...

x$name2 <- 1:nrow(x)
ggplot(x, aes(x = factor(name2), y = val)) + theme_bw() + geom_bar(stat = "identity") + 
             scale_x_discrete(labels=x$name)
Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32
  • i tried this with a time series data where the same date is repeated more than once in the x-axis, this solution simply stacks the repeating values into one. Doesn't show them separately somehow. – samsamara Dec 16 '20 at 01:42
  • @samsamara It is hard to tell without seeing your data. It would probably be best for you to ask this as a separate question, with a reproducible example and a clear description of what you are trying to achieve. – Andrew Gustar Dec 16 '20 at 07:15
  • No worries. I posted a question and got the answer. It was just that I needed to use 'position_dodge()' in the geom object. https://stackoverflow.com/questions/65316274/how-to-have-separate-columns-for-duplicate-x-axis-values-in-geom-col – samsamara Dec 17 '20 at 00:53
0

Actually, simply add the following setting xlab(x$name)

ggplot(x, aes(x = name, y = val)) + theme_bw() + geom_bar(stat = "identity") + xlab(x$name)
keepAlive
  • 6,369
  • 5
  • 24
  • 39