2013-09-26 52 views
2

我试图绘制下列数据的x轴设置标签:上的曲线图

ph1 = c(5, 6, 7, 8, 9) 
ph2 = ph3 = ph1 

e1 = c(0.191, 0.154, 0.179, 0.073, 0.009) 
e2 = c(0, 0.029, 0.054, 0.055, 0.024) 
e3 = c(0.019, 0.027, 0.063, 0.029, 0.039) 

set.seed(1) 
df1 <- data.frame(e1 = sort(runif(5, 0.05, 0.25)), 
        e2 = sort(runif(5, 0.05, 0.25)), 
        e3 = sort(runif(5, 0.05, 0.25)), 
        ph1 = sort(runif(5, 1, 100)), 
        ph2 = sort(runif(5, 1, 100)), 
        ph3 = sort(runif(5, 1, 100)) 
        ) 
### reshape this to give a column indicating group 
df2 <- with(df1, 
     as.data.frame(cbind(c(ph1, ph2, ph3), 
          c(e1, e2, e3), 
          rep(seq(3), each=5)) 
         )) 
colnames(df2) <- c("ph","maltose_in_mg","team") 
df2$team <- as.factor(df2$team) 
library(ggplot2) 
ggplot(df2, aes(x=ph, y=maltose_in_mg, col=team)) + geom_line() 

...与在x轴为标签的pH值(5至9)。不幸的是,正在从0到100

编辑(:非功能性的解决方案注):显示的标签

df1 <- data.frame(e1 = sort(runif(5, 0.05, 0.25)), 
        e2 = sort(runif(5, 0.05, 0.25)), 
        e3 = sort(runif(5, 0.05, 0.25)), 
        ph1 = sort(runif(1, 5, 9)), 
        ph2 = sort(runif(1, 5, 9)), 
        ph3 = sort(runif(1, 5, 9)) 
       ) 
+1

你'ph' df2'范围从0到100 –

+0

你好。你能检查我的编辑吗?我的编辑没有解决问题,我卡住了。谢谢。 – CaitlinG

+0

使用新的数据框,轴是正确的(它们的范围从我的机器上的5到8.5) –

回答

2

我想这是你想要做什么,但如果它不是,请纠正我。

我已将pH值设置在x轴上,麦芽糖以毫克为单位在y轴上。

我还从ggthemes包中添加了一个主题,这使得它很漂亮。还有其他主题可以在我放入代码评论的链接中找到。

最后,我限制了X轴与coord_cartesian(< - 这就是我想你要找的,在画面上显示的范围控制)然后scale_colour_discrete把一个好看的标题上的传说。

接下来我添加了一个标题ggtitle和轴标签。 theme_wsj()具有ggplot设置,只需在R控制台中输入theme_wsj()即可查看。默认情况下是隐藏轴标签,我必须用theme()函数及其内部的位来覆盖它。

ggplot2是一个了不起的包。你可以在这里阅读所有关于它:在'http://docs.ggplot2.org/current/

install.packages("ggthemes") 
library(ggthemes) 

ph1 = c(5, 6, 7, 8, 9) 
ph2 = ph3 = ph1 

e1 = c(0.191, 0.154, 0.179, 0.073, 0.009) 
e2 = c(0, 0.029, 0.054, 0.055, 0.024) 
e3 = c(0.019, 0.027, 0.063, 0.029, 0.039) 

set.seed(1) 
df1 <- data.frame(e1 = sort(runif(5, 0.05, 0.25)), 
        e2 = sort(runif(5, 0.05, 0.25)), 
        e3 = sort(runif(5, 0.05, 0.25)), 
        ph1 = sort(runif(1, 5, 9)), 
        ph2 = sort(runif(1, 5, 9)), 
        ph3 = sort(runif(1, 5, 9)) 
) 

df2 <- with(df1, 
      as.data.frame(cbind(c(ph1, ph2, ph3), 
           c(e1, e2, e3), 
           rep(seq(3), each=5)) 
      )) 
colnames(df2) <- c("ph", "maltose_in_mg", "team") 
df2$team <- as.factor(df2$team) 
library(ggplot2) 
ggplot(df2, aes(x = ph, y = maltose_in_mg, colour = team)) + 
    geom_line(size = 2) + 
    coord_cartesian(xlim = c(5, 9)) + # this is how you limit the axis range displayed, you can do the y, too with ylim = c(0, 1) 
    scale_colour_discrete(name = "Team") + 
    theme_wsj() + # find more themes here: https://github.com/jrnold/ggthemes 
    ggtitle("pH by Team") + 
    ylab("Maltose in Milligrams") + 
    xlab("pH") + 
    theme(axis.title = element_text(angle = 90, vjust = -0.075), 
     axis.text = element_text(size = 20), 
     legend.text = element_text(size = 15)) 

+1

也许添加一个数字,所以我们可以看到解决方案? –