簡體   English   中英

ggplot2上的圖例帶有3個圖形(在x軸上)

[英]Legend on ggplot2 with 3 graphs (on the x-axis)

如何為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

需要圖例的地塊

在此處輸入圖片說明

我建議您避免每列對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()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM