-1

I'm trying to display specific values on x-axis while plotting a line plot on with ggplot2. In my table, I have the num values which are quite distant from each other, that's why I want to plot them as discrete values.

line <- ggplot(lineplot, aes(value,num, colour=attribute))
line + geom_line()

Hope I've been clear, I'm a very beginner, apologies in advance for the question

example table:
    num value   attribute
a   0   0.003   main
b   1   0.003   low
c   0   0.003   high
d   0   0.6 main
e   9   0.6 low
f   3   0.6 high
g   2   0.9 main
h   2   0.9 low
I   2   0.9 high

x-axis: what i get:

0.003                                       0.6           0.9

i want:

0.003         0.6         0.9
mightaskalot
  • 167
  • 1
  • 14
  • 2
    Remove `lineplot$` from inside `aes()`. I find your question very unclear. – Roland Feb 14 '18 at 11:50
  • Look into `?ggplot2::theme` The argument `axis.text.x` might be suitable. – LAP Feb 14 '18 at 11:55
  • Not clear, either you want to [subset the data](https://stackoverflow.com/questions/1686569/filter-data-frame-rows-by-a-logical-condition) before plotting or use custom [x-axis values](https://stackoverflow.com/questions/5096538/customize-axis-labels) – zx8754 Feb 14 '18 at 12:07
  • Indeed is exactly what Chase answered in https://stackoverflow.com/questions/5096538/customize-axis-labels but i want to do that with ggplot – mightaskalot Feb 14 '18 at 12:19
  • A clearer reproducible example would help others to help you. – Prradep Feb 14 '18 at 13:59
  • added and example – mightaskalot Feb 14 '18 at 15:04

2 Answers2

2

If you want the x axis to be treated like a discrete factor then you have to add the group aesthetic to tell ggplot2 which points to connect with a line.

df <- read.table(text = "num value   attribute
0   0.003   main
1   0.003   low
0   0.003   high
0   0.6 main
9   0.6 low
3   0.6 high
2   0.9 main
2   0.9 low
2   0.9 high", header = TRUE)

ggplot(df, aes(x = factor(value), y = num, group = attribute, color = attribute)) + 
  geom_line()

enter image description here

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104
0

try to force x-axis to be as factor and not numeric

line <- ggplot(lineplot, aes(factor(value),num, colour=attribute))
line + geom_line()

Is that what you want ?

Nicolas Rosewick
  • 1,938
  • 4
  • 24
  • 42
  • Correct, but if i do that i lose the line (but not the points with geom_point()). i get the error: "geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?" – mightaskalot Feb 14 '18 at 15:17
  • @mightaskalot And when you add the group aesthetic it works. See [here.](https://stackoverflow.com/a/48798651/4975218) – Claus Wilke Feb 15 '18 at 00:59
  • Yes forgot to put the group aes. Check @Claus answer. – Nicolas Rosewick Feb 15 '18 at 07:56