在ggplot2中添加x和y轴标签

时间:2012-05-03 20:20:20

标签: r label ggplot2

如何更改此图表上的x和y标签?

library(Sleuth2)
library(ggplot2)
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
p + geom_point(aes(size= nitrogen)) + 
    scale_area() + 
    opts(title = expression("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)"), 
         subtitle="n=41")

2 个答案:

答案 0 :(得分:175)

[注意:编辑以使ggplot语法现代化]

您的示例无法重现,因为没有ex1221newex1221中有Sleuth2,所以我想这就是您的意思。此外,您不需要(也不应该)将列拉出来发送到ggplot。一个优点是ggplot可以直接与data.frame一起使用。

您可以使用xlab()ylab()设置标签,或将其作为scale_*.*电话的一部分。

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

另一种指定标签的方法(如果您不改变比例的任何其他方面,则很方便)使用labs功能

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

给出与上面相同的数字。

答案 1 :(得分:0)

因为没有提供数据ex1221new,所以我创建了一个虚拟数据并将其添加到数据帧中。另外,提出的问题在代码中几乎没有变化,例如ggplot软件包已弃用了

"scale_area()" and nows uses scale_size_area()
"opts()" has changed to theme()

在我的回答中,我将情节存储在mygraph变量中,然后使用

mygraph$labels$x="Discharge of materials" #changes x axis title
       mygraph$labels$y="Area Affected" # changes y axis title

工作已经完成。下面是完整的答案。

install.packages("Sleuth2")
library(Sleuth2)
library(ggplot2)

ex1221new<-data.frame(Discharge<-c(100:109),Area<-c(120:129),NO3<-seq(2,5,length.out = 10))
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
mygraph<-p + geom_point(aes(size= nitrogen)) + 
  scale_size_area() + ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")+
theme(
 plot.title =  element_text(color="Blue", size=30, hjust = 0.5), 

 # change the styling of both the axis simultaneously from this-
 axis.title = element_text(color = "Green", size = 20, family="Courier",)
 

   # you can change the  axis title from the code below
   mygraph$labels$x="Discharge of materials" #changes x axis title
   mygraph$labels$y="Area Affected" # changes y axis title
   mygraph



   

此外,您可以根据上面使用的相同公式更改标签标题-

mygraph$labels$size= "N2" #size contains the nitrogen level 
相关问题