codememo

ggplot에서 범례(텍스트) 레이블 편집

tipmemo 2023. 6. 27. 22:14
반응형

ggplot에서 범례(텍스트) 레이블 편집

설명서와 StackOverflow를 몇 시간 동안 살펴보았지만 해결책이 없어 문제를 해결할 수 없습니다.사용 시ggplot범례의 텍스트가 내 데이터 프레임에 있더라도 올바른 텍스트를 가져올 수 없습니다.난 시도했다.scale_colour_manual,scale_fill_manual에 대해 다른 값을 가진labels=예를 들어c("T999", "T888")", "cols".

내 코드는 다음과 같습니다.

T999 <- runif(10, 100, 200)
T888 <- runif(10, 200, 300)
TY <- runif(10, 20, 30)
df <- data.frame(T999, T888, TY)


ggplot(data = df, aes(x=T999, y=TY, pointtype="T999")) + 
       geom_point(size = 15, colour = "darkblue") + 
       geom_point(data = df, aes(x=T888, y=TY), colour = 'red', size = 10 ) + 
       theme(axis.text.x = element_text(size = 20), axis.title.x =element_text(size = 20),   axis.text.y = element_text(size = 20)) +
       xlab("Txxx") + ylab("TY [°C]") + labs(title="temperatures", size = 15) + 
       scale_colour_manual(labels = c("T999", "T888"), values = c("darkblue", "red")) +    theme(legend.position="topright")

다음은 위 코드의 그래픽 출력입니다.

graphical output of ggplot code

도움을 주시면 감사하겠습니다!

@Henrik가 언급한 튜토리얼은 다음을 사용하여 플롯을 만드는 방법을 배울 수 있는 훌륭한 자료입니다.ggplot2꾸러미

데이터의 예:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

결과:

enter image description here

@user2739472가 코멘트에서 언급한 바와 같이:ggplot의 기본 팔레트의 색상이 아닌 범례 텍스트 레이블만 변경하려는 경우scale_color_hue(labels = c("T999", "T888"))대신에scale_color_manual().

범례 제목은 특정 미학에 따라 레이블을 지정할 수 있습니다.

이는 다음을 사용하여 달성할 수 있습니다.guides()또는labs()의 기능.ggplot2(여기와 여기에 더 있음).미적 매핑을 사용하여 가이드/레전드 속성을 추가할 수 있습니다.

다음은 다음을 사용하는 예입니다.mtcars데이터 세트 및labs():

ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
  geom_point() +
  labs(x="miles per gallon", y="displacement", size="horsepower", 
       col="# of cylinders", shape="# of gears")

enter image description here

다음을 사용하여 OP의 질문에 답변guides():

# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")

# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) + 
  geom_point(size=5) +
  labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  guides(color=guide_legend("my title"))  # add guide properties by aesthetic

enter image description here

언급URL : https://stackoverflow.com/questions/23635662/editing-legend-text-labels-in-ggplot

반응형