将颜色符号添加到轴标签

时间:2015-10-13 08:31:09

标签: r ggplot2

我有一个带有相同颜色框的盒子图。我想用实验室()命名轴,并在情节框的颜色中添加一个小符号。

sector <- c("HY", "HY (ETFs)", "IG", "IG (ETFs)", "Loan", "Equities")
YTD_percent <- c(-0.2, 0.5, 0.05, 0.2, -0.1, 0.1)
data1 <- data.frame(sector, YTD_percent)

ggplot(data1, aes(sector, YTD_percent)) + 
  geom_bar(stat="identity", color="#00669C", fill="#00669C", width=0.7) +
  labs(x = NULL, y = NULL, title = "Plot Title") +
  coord_flip() +
  theme_bw() + 
  theme(axis.text.y=element_blank(),
        axis.ticks.y = element_blank()
        )+
  guides(fill = guide_legend(keywidth = 1, keyheight = 1)) +
  scale_y_continuous(breaks=pretty_breaks(), expand = c(.05, .05), labels=percent) +
  geom_text(aes(label = sector , y = YTD_percent), hjust = ifelse(data_ff$YTD_percent >= 0, -0.1, 1.1), size=6)

enter image description here

这就是轴最终应该是什么样子:

enter image description here

1 个答案:

答案 0 :(得分:3)

你可以加入你的美学绘图并稍微调整一下传奇:

library(ggplot2)
library(scales)
ggplot(data1, aes(sector, YTD_percent, fill = "YTD (in %)")) + 
  geom_bar(stat="identity", color="#00669C",  width=0.7) +
  scale_fill_manual(values = c("YTD (in %)" = "#00669C")) + 
  labs(x = NULL, y = NULL, title = "Plot Title", fill = "") +
  coord_flip() +
  theme_bw() + 
  theme(axis.text.y=element_blank(),
        axis.ticks.y = element_blank(),
        legend.position = "bottom"
  )+
  guides(fill = guide_legend(keywidth = 1, keyheight = 1)) +
  scale_y_continuous(breaks=pretty_breaks(), expand = c(.05, .05), labels=percent) +
  geom_text(aes(label = sector , y = YTD_percent), hjust = ifelse(data1$YTD_percent >= 0, -0.1, 1.1), size=6)

enter image description here