控制ggplot图例中的线型,颜色和标签 [英] Controlling linetype, color and label in ggplot legend

查看:141
本文介绍了控制ggplot图例中的线型,颜色和标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在设置自定义线型和颜色的地块上设置自定义图例标签时遇到了问题。对于



scale_linetype_manual() scale_color_manual()中设置标签会创建两个独立的图例。具有正确的线条的人将永远是无色的。另一方面,具有正确颜色的人不能正确表示线型(只有实线)。



有没有办法在ggplot2中同时控制颜色,线条类型和图例标签?或者,这是一个包的限制,我应该从getgo的数据框中正确指定标签? 解决方案

scale_linetype_manual() scale_color_manual()标签相同。

(pre> library(ggplot2)

df < - data.frame(x = rep(1:2,2),y = c
treatment = c(rep(one,2),rep(two,2)))

ggplot(df,aes( x = x,y = y,color = treatment,linetype = treatment))+
geom_line()+
scale_linetype_manual(values = c(1,3),
labels = c(治疗一,治疗二))+
scale_color_manual(values = c(black,red),
labels = c(Treatment one,Treatment two))


I'm having trouble setting custom legend labels on plots where I have also previously specified custom linetypes and colors. There is a similar question on stackoverflow that deals with custom legends for linetypes and line colors. However, once you wish to specify legend labels on top of the two aforementioned attributes ggplot2 seemingly starts to break down.

Here's my minimally reproducible example:

library(ggplot2)

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
           treatment = c(rep("one", 2), rep("two", "2")))

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
  geom_line() +
  scale_linetype_manual(values = c(1, 3),
                        labels = c("Treatment one", "Treatment two")) +
  scale_color_manual(values = c("black", "red"))

The above code results in the following graph

Setting labels in either scale_linetype_manual() or scale_color_manual() results in two seperate legends being created. The one that has the correct dashing of lines will always be colorless. The one with correct colors, on the other hand, will not represent the linetypes correctly (only solid lines).

Is there a way to control color, line type and legend labels all at once in ggplot2? Or is this a limitation of the package where I should just specify the labels correctly in the dataframe from the getgo?

解决方案

Make the label the same for both scale_linetype_manual() and scale_color_manual().

library(ggplot2)

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
                 treatment = c(rep("one", 2), rep("two", "2")))

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
  geom_line() +
  scale_linetype_manual(values = c(1, 3),
                        labels = c("Treatment one", "Treatment two")) +
  scale_color_manual(values = c("black", "red"),
                     labels = c("Treatment one", "Treatment two"))

这篇关于控制ggplot图例中的线型,颜色和标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆