如何在x轴上为以下3个图形创建图例?谢谢你的帮助!
library("ggplot2")
theme_set(theme_bw())# White background for plots
#creating 3 X 4 data frame (reduced from 50 x4 for 50 states)
state_name = as.factor(c("State_A","State_B","State_C"))
mw = c(7.25,11.5,7.25)
mw_tip = c(2.13,2.63,5.50)
mw_gap = mw-mw_tip
wage_data = data.frame(state_name,mw,mw_tip,mw_gap)
wage_data
str(wage_data)
#Re-order the df according to mw, mw_tip, mw_gap,
#therefore, states won'd be listed alphabetically
#below, #ordering by mw, mw_tip, and gap
wage_data = wage_data[order(wage_data$mw,wage_data$mw_tip,wage_data$mw_gap),]
wage_data$state_name=factor(wage_data$state_name, as.character(unique(wage_data$state_name)))
wage_data #now ordered as State_A, State_C, State B that is plotted below
#Below, I plot 3 graphs: mw, mw_tip, mw_gap on the x-axis
(fig=ggplot(wage_data,aes(y=state_name,x=mw)))
(fig=fig+labs(x="Dollars per hour",y="50 U.S. States"))
(fig=fig+geom_point(size=3,color="green"))
(fig=fig+geom_point(aes(x=mw_tip),size=3,color="red",shape=17))
(fig=fig+geom_point(aes(x=mw_gap),size=3,color="orange",shape=15))
(fig=fig+scale_x_continuous(breaks=seq(0,11.5,0.5)))
#Below, legend does not work! I also tried with scale...
#and with aes, nothing worked for me
(fig=fig+theme(legend.position = c(0.9,0.15),legend.justification = c(1,0), legend.title = element_blank()))
#End of code
需要传奇的地块
答案 0 :(得分:0)
我建议你不要为每一列调用goem_point
;相反,您可以在绘图之前将数据从宽到长重新整形,并使用what
键作为颜色美学。这会自动引入相应的图例。
state_name <- factor(c("State_A", "State_B", "State_C"))
mw <- c(7.25, 11.5, 7.25)
mw_tip <- c(2.13, 2.63, 5.50)
mw_gap <- mw - mw_tip
wage_data <- data.frame(state_name, mw, mw_tip, mw_gap)
library(tidyverse);
wage_data %>%
gather(what, value, -state_name) %>%
ggplot(aes(value, state_name, colour = what, group = what)) +
geom_line()
或使用geom_point
使用不同的符号:
wage_data %>%
gather(what, value, -state_name) %>%
ggplot(aes(value, state_name, colour = what, shape = what)) +
geom_point()