为图例添加特定标签

时间:2016-05-22 15:36:29

标签: r ggplot2

目标:在图例中添加数字标签(图上的条数),例如1.Company X
2.公司Y
3.Company Z

library(ggplot2)
require(scales)

companies = c('Company X','Company Y','Company Z')
profits = c(100,200,300)
data1 = data.frame(companies,profits)

CP <- ggplot(data1, aes(x = data1$companies,y = data1$profits,fill =data1$companies )) +
    geom_bar(stat = 'identity') + 
    scale_x_discrete(name = "Companies",labels = 1:length(data1$companies))

目前我有enter image description here

2 个答案:

答案 0 :(得分:1)

您可能正在寻找的是粘贴:

newcompanies <- paste(1:50,companies,sep=".")

个人(风格)建议: 搜索如何将颜色更改为一个颜色范围。对于50家公司来说,这个颜色范围会让人感到困惑。

答案 1 :(得分:1)

您可以使用seq_alongpaste制作您想要的情节,如下所示:

ggplot(data1, aes(x=seq_along(companies), weight=profits,
                  fill=paste(seq_along(companies), companies))) + 
  geom_bar() +
  scale_fill_discrete("Companies") +
  labs(x="Company Labels", y="Count")

enter image description here