gpt4 book ai didi

r - 基于条件的部分粗体ggplot2指南标签

转载 作者:行者123 更新时间:2023-12-05 06:36:36 26 4
gpt4 key购买 nike

我有一些要绘制的整洁数据,将两列合并为分组。

在图例中,我想打印其中一列中的条目之一大胆的脸。

这是一个最小的工作示例:

library(ggplot2)

plot.data <- data.frame(x=1:10, y=1:10,
class1=rep(letters[1:2], 10),
class2=rep(LETTERS[1:2], each=5))

# This class should be displayed in bold
# Might be subject to change; consider it a function parameter
class2.bold <- "A"

# This is the default
# Note that the used classes are automagically determined from the data
ggplot(plot.data, aes(x, y)) +
geom_point(aes(color=paste(class1, class2, sep="/"))) +
scale_color_discrete("class")

# This is what I want
# Note that it only works because I know the data used in this example
ggplot(plot.data, aes(x, y)) +
geom_point(aes(color=paste(class1, class2, sep=" / "))) +
scale_color_discrete("class",
label=c(expression(a / bold(A)),
expression(a / B),
expression(b / bold(A)),
expression(b / B)))

如何利用 class2.boldplot.data 获得第二个图仅(即在编写代码时不进一步了解其内容)?

例如,当我将 class2.bold 更改为 "B" 并将更多数据行添加到plot.data 具有附加的 class1class2 值/组合,我仍然希望绘图命令无需手动调整即可工作。

最佳答案

这对我有用。可能有更快的方法,但这可以实现。

您的代码:

  plot.data <- data.frame(x=1:10, y=1:10,
class1=rep(letters[1:2], 10),
class2=rep(LETTERS[1:2], each=5))

# This class should be displayed in bold
# Might be subject to change; consider it a function parameter
class2.bold <- "A"

# This is the default
# Note that the used classes are automagically determined from the data
ggplot(plot.data, aes(x, y)) +
geom_point(aes(color=paste(class1, class2, sep="/"))) +
scale_color_discrete("class")

对于粗体标签:

 #get unique labels
legend_labs <- unique(paste(plot.data$class1, plot.data$class2, sep="/"))

#order them in alphabetical order
legend_labs <- legend_labs[order(legend_labs)]

#Bold the correct letters
legend_labs <- sub(pattern = class2.bold,
replacement = paste0("bold(",class2.bold,")"),
legend_labs)

#make them expressions
legend_labs <- lapply(parse(text = legend_labs), as.expression)

#plot
ggplot(plot.data, aes(x, y)) +
geom_point(aes(color=paste(class1, class2, sep=" / "))) +
scale_color_discrete("class",
label=legend_labs)

编辑:

如果你想加粗更多的字母,请改用第三步

#Bold the correct letters
for (i in 1:length(class2.bold)) {
legend_labs <- sub(pattern = class2.bold[i],
replacement = paste0("bold(",class2.bold[i],")"),
legend_labs)
}

关于r - 基于条件的部分粗体ggplot2指南标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48924673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com