R ggplot2图例文字颜色
我对ggplot2中的图例文本(每个组名都有相应的颜色)着色有一个问题。这是我想要的输出: 我正在使用这些数据:R ggplot2图例文字颜色,r,ggplot2,R,Ggplot2,我对ggplot2中的图例文本(每个组名都有相应的颜色)着色有一个问题。这是我想要的输出: 我正在使用这些数据: df <- data.frame(group = c("Group 1","Group 2","Group 3") , value = c(1000000, 300000, 100000) , value_format = c("1.000.000", "300.000", "100.000")
df <- data.frame(group = c("Group 1","Group 2","Group 3")
, value = c(1000000, 300000, 100000)
, value_format = c("1.000.000", "300.000", "100.000")
, weigth = c("71,4%", "21,4%", "7,14%")
, stringsAsFactors = F)
lables <- paste(paste(df$group, df$value_format, sep = ": "), df$weigth, sep = "\n")
df我已经使用@Axeman建议的annotate
函数解决了这个问题。这是我的最终代码(带有一些调整技巧):
库(ggplot2)
图书馆(网格)
库(外部字体)
g忘记图例和使用它可能更容易。@Axeman,我是ggplot的新手,所以需要查看它!但这似乎是一个好主意。如果在绘图区域外进行注释时遇到问题,请查看cowplot
软件包,该软件包提供了更多的功能。@Axeman,谢谢您的评论!我来看看。看来,annotate
将起作用
library(ggplot2)
library(grid)
library(extrafont)
g <- ggplot(data=df, aes(x = 1, y = value, fill = factor(group)))
g <- g + geom_bar(position="stack",stat="identity")
g <- g + theme(
plot.margin = unit(c(0, 0, 0, 0), "in")
, axis.line = element_blank()
, axis.text.x = element_blank()
, axis.text.y = element_blank()
, axis.ticks = element_blank()
, axis.title.x = element_blank()
, axis.title.y = element_blank()
, panel.background = element_blank()
, panel.border = element_blank()
, panel.grid.major = element_blank()
, panel.grid.minor = element_blank()
, plot.background = element_blank()
, legend.position="top"
, legend.title = element_blank()
, legend.text.align = .5
, legend.text = element_text(colour = c("#595959", "#E26B0A", "#00B0F0")
, family = "Arial"
, size = 11, face = "bold")
, legend.key.size = unit(0.5, "cm")
)
g <- g + scale_fill_manual(values=c("#595959", "#E26B0A", "#00B0F0"),
breaks=c("Group 1","Group 2","Group 3"),
labels=lables)
g <- g + coord_flip()
g
library(ggplot2)
library(grid)
library(extrafont)
g <- ggplot(data = df, aes(x = 1, y = value, fill = factor(group))) +
geom_bar(position = "stack", stat = "identity") +
theme(plot.margin = unit(c(.5, 0.2, 0, 0.1), "in")
, axis.line = element_blank()
, axis.text.x = element_blank()
, axis.text.y = element_blank()
, axis.ticks = element_blank()
, axis.title.x = element_blank()
, axis.title.y = element_blank()
, panel.background = element_blank()
, panel.border = element_blank()
, panel.grid.major = element_blank()
, panel.grid.minor = element_blank()
, plot.background = element_blank()
, legend.position=""
) +
scale_fill_manual(values=c("#595959", "#E26B0A", "#00B0F0"),
breaks=c("Group 1","Group 2","Group 3"),
labels=lables) +
coord_flip() +
annotate("text", label=lables[1], x=1.8, y = df$value[1]/2
, fontface = "bold", color = "#595959", family="Arial", size = 4.5) +
annotate("text", label=lables[2], x=1.8, y = sum(df$value)-400000
, fontface = "bold", color = "#E26B0A", family="Arial", size = 4.5) +
annotate("text", label=lables[3], x=1.8, y = sum(df$value)-100000
, fontface = "bold", color = "#00B0F0", family="Arial", size = 4.5)
g