Making line plot with discrete x-axis in ggplot2

淺唱寂寞╮ 提交于 2019-12-02 18:03:32

问题


I am building a ggplot2 figure with a facet grid. On my Y-axis are percentages, and my X-axis is the concentration (in numbers). Each facet has 3 groups (0, 24 and 48 hours)

ggplot(data=MasterTable, aes(x=Concentration, y=Percentage, group=Time)) + 
  geom_point() + 
  geom_line() + 
  facet_grid(Chemicals ~ Treatments) 

This generates a continuous x-axis. Since the values are not evenly spread out, I would prefer a discrete axis to better visualize my data. I followed the following tutorial with no luck. The first figure is exactly what I am trying to do.

I also tried formatting the axis:

scale_x_discrete(labels("0", "0.1", "2", "50"))

and formatting the line:

geom_line(aes(Time))

and following this tutorial.

I think this problem is that the values on the x-axis are integers rather than strings. This makes the default axis continuous. How can I change this?? I am sure the solution is simple, I just can't figure it out.

Thanks in advance!


回答1:


On this page they make the following modification df2$dose<-as.factor(df2$dose). You can try to modify your x-axis as df2$Concentration<-as.factor(df2$Concentration)

or like this:

ggplot(data=MasterTable, aes(x=factor(Concentration), y=Percentage, group=Time)) + 
  geom_point() + 
  geom_line() + 
  facet_grid(Chemicals ~ Treatments) 


来源:https://stackoverflow.com/questions/45342212/making-line-plot-with-discrete-x-axis-in-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!