0

Using scale shape manual in ggplot, I created different values for three different types of factories (squares, triangles, and circles), which corresponds to North, South, and West respectively. Is it possible to have the North/South/West labels in the legend without creating three different data frames for each region? Can I add these labels to the original data frame?

I have one data frame for a plot (as recommended by the ggplot2 book), and with my code below, the default legend lists every row in my data frame, which is repetitive and not what I want.

Basically, I would like to know the best way to label these regions in the plot. The only reason I would like to maintain one data frame is because the code will be easy to use over and over again by just switching the data frame (the benefit of one df mentioned in the ggplot2 book).

I think part of the problem is that I am using scale shape manual to assign values to each point individually. Should I put the North/South/West labels in my data frame and alter my scale shape manual? If so, what is the best way to accomplish this?

Please let me know if my question is unclear. My code is below, and it replicates my plot as it stands. Thanks.

#Data frame
points <- c(3,5,4,7,12)
bars <- c(.8,1.2,1.4,2.1,4)
points_df<-data.frame(points) 
row.names(points_df) <- c( "Factory 1","Factory 2","Factory 3","Factory 4","Factory 5" )

df<-data.frame(Output=points,Errors=bars,lev.names= rownames(points_df))
df$lev.names<-factor(df$lev.names,levels=df$lev.names[order(df$Output)])

# GGPLOT #
library(ggplot2)
library(scales)

p2 <- ggplot(df,aes(lev.names,Output,shape=lev.names))

p2 <- p2 +geom_errorbar(aes(ymin=Output-Errors, ymax=Output+Errors), width=0,color="gray40", lty=1, size=0) 

p2 <- p2 + geom_point(aes(size=2)) 

p2 <- p2  + scale_shape_manual(values=c(6,7,6,1,1))

p2 <- p2 + theme_bw() + xlab(" ") + ylab("Output")

p2 <- p2 + opts(title = expression("Production"))
p2 <- p2+ coord_flip()
print(p2)
4

1 回答 1

1

是的,将位置放在您的 data.frame 中并在 aes 映射中使用它:

df$location <- c("North","South","North","West","West")

p2 <- ggplot(df,aes(lev.names,Output,shape=location)) +
  geom_errorbar(aes(ymin=Output-Errors, ymax=Output+Errors), 
                width=0,color="gray40", lty=1, size=0) +
  geom_point(size=3) + 
  theme_bw() + xlab(" ") + ylab("Output") +
  ggtitle(expression("Production")) +
  coord_flip()
print(p2)

我还修复了一些其他的东西(例如,opts不推荐使用并且您不想映射size,而是设置它)。

于 2013-07-11T19:26:35.377 回答