ggplot2图例文字颜色

时间:2015-10-08 15:00:26

标签: r ggplot2

我在使用ggplot2中的图例文本(每个组名称具有相应颜色)时遇到问题。这是我想要的输出:

enter image description here

我正在使用这些数据:

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")

这是我更好的近似代码:

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

从这一点来说,我无法做出三件事:

  1. 为每组对应的文字着色(请注意,我在element_text内为legend.text引入了颜色向量,但仅采用第一个值
  2. 删除legend.key(带颜色的框)
  3. 在栏上分发图例文字
  4. 感谢任何帮助

1 个答案:

答案 0 :(得分:0)

我已使用R> l <- list(key = 1) R> l$k [1] 1 R> options("warnPartialMatchDollar"=TRUE) R> l$k [1] 1 Warning message: In l$k : partial match of 'k' to 'key' R> 函数解决了问题,正如@Axeman在下面建议的那样。这是我的最终代码(有一些调整的技巧):

$manufacturer_in_category = Db::getInstance()->executeS('
    'SELECT p.id_manufacturer
     FROM `'._DB_PREFIX_.'product` p 
    '.Shop::addSqlAssociation('product', 'p').' 
    LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON p.`id_product` = cp.`id_product` 
    WHERE cp.`id_category` = '.(int) $id_category.' 
    AND product_shop.`visibility` IN ("both", "catalog") 
    AND product_shop.`active` = 1
    GROUP BY p.id_manufacturer
');

foreach($manufacturer_in_category as $manufacturer) {
// Here you go ...
}

感谢&#39;!小号