ggplot2 - 在图例中获取注释

时间:2017-12-12 04:17:00

标签: r ggplot2

我正在使用数据框并使用ggplot生成饼图。

Make

这给了我一个饼图如下 - 如何添加%份额以及honda (45%)标签,例如honda而不仅仅是CRSFactory crsFactory = ReferencingFactoryFinder.getCRSFactory(null); CoordinateReferenceSystem targetCRS = null; CoordinateReferenceSystem sourceCRS = null; Geometry transCoordGeometry = null; try { targetCRS = CRS.decode("EPSG:32632"); sourceCRS = CRS.decode("EPSG:4326"); } catch (FactoryException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } MathTransform transform = null; try { transform = CRS.findMathTransform(sourceCRS, targetCRS); transCoordGeometry = JTS.transform(orgGeometry, transform); } catch (FactoryException | MismatchedDimensionException | TransformException e) { // TODO Auto-generated catch block e.printStackTrace(); }

enter image description here

1 个答案:

答案 0 :(得分:4)

这可以通过向breaks添加labelsscale_fill_brewer来实现。

首先,您将Make映射到fill,以便控制使用fill_scale所需的颜色。其次,如果您想提供自定义图例条目,请定义breaks中图例中的关键字以及labels中的新名称:

library(ggplot2)


ggplot(dfc[1:10, ], aes("", share, fill = Make)) +
  geom_bar(width = 1, size = 1, color = "white", stat = "identity") +
  coord_polar("y") +
  geom_text(aes(label = paste0(round(share), "%")), 
            position = position_stack(vjust = 0.5)) +
  labs(x = NULL, y = NULL, fill = NULL, 
       title = "Market Share") +
  guides(fill = guide_legend(reverse = TRUE)) +
  theme_classic() +
  theme(axis.line = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        plot.title = element_text(hjust = 0.5, color = "#666666")) +
   scale_fill_brewer(palette = "Paired",
                     labels = rev(paste0(dfc$Make, " (", round(dfc$share), "%)")),
                     breaks = rev(dfc$Make))

enter image description here