fix x-axis ordering in ggplot2

2020-03-31 06:04发布

问题:

I have the following data

dftmp
   z.transient kprimes       groupname
1    -1.244061      10    k=9.8,p=56.4
2    -0.995249      20    k=9.8,p=56.4
3    -0.746437      30    k=9.8,p=56.4
4    -0.497625      40    k=9.8,p=56.4
5    -0.248812      50    k=9.8,p=56.4
6            0      60    k=9.8,p=56.4
7     0.248812      70    k=9.8,p=56.4
8     0.497625      80    k=9.8,p=56.4
9     0.746437      90    k=9.8,p=56.4
10    0.995249     100    k=9.8,p=56.4
11    1.244061     110    k=9.8,p=56.4
12   -1.244061     100 k=103.2,p=155.5
13   -0.995249     200 k=103.2,p=155.5
14   -0.746437     300 k=103.2,p=155.5
15   -0.497625     400 k=103.2,p=155.5
16   -0.248812     500 k=103.2,p=155.5
17           0     600 k=103.2,p=155.5
18    0.248812     700 k=103.2,p=155.5
19    0.497625     800 k=103.2,p=155.5
20    0.746437     900 k=103.2,p=155.5
21    0.995249    1000 k=103.2,p=155.5
22    1.244061    1100 k=103.2,p=155.5
23   -1.244061    1000   k=786.9,p=849
24   -0.995249    2000   k=786.9,p=849
25   -0.746437    3000   k=786.9,p=849
26   -0.497625    4000   k=786.9,p=849
27   -0.248812    5000   k=786.9,p=849
28           0    6000   k=786.9,p=849
29    0.248812    7000   k=786.9,p=849
30    0.497625    8000   k=786.9,p=849
31    0.746437    9000   k=786.9,p=849
32    0.995249   10000   k=786.9,p=849
33    1.244061   11000   k=786.9,p=849

I would like to plot it with ggplot2

p <- ggplot(dftmp, aes(x=z.transient, y=kprimes, group=groupname))
p <- p + geom_line(aes(colour=groupname), size=2) 
p <- p + scale_y_log10()

But, ggplot2 seems to be ordering the factor as starting from 0, then alternatiing negative and positive, such that I get a wavy line in each plot:

How do I reorder the x factor. Also, how do I specify the axis limits for the y axis?

回答1:

That's because your z.transient is a factor like you said. It seems to me that its a continuous variable no? If so, convert it from a factor to the value (see ?factor).

dftmp$z.transient <- as.numeric(levels(dftmp$z.transient))[dftmp$z.transient]

Also, as your data is now, if I use it directly the plot looks fine since z.transient is numeric. Try it, use:

dftmp <- read.table('clipboard')

Then follow your plotting steps...

As far as axis limits, this post should steer you in the right direction.



标签: r ggplot2