The following data frame contains a numerical variable representing the count of some event and the corresponding label for each value.
value | group |
---|---|
10 | G1 |
23 | G2 |
15 | G3 |
18 | G4 |
geom_bar
or geom_col
and coord_polar
Basic pie chart
A pie chart in ggplot is a bar plot plus a polar coordinate. You can use geom_bar
or geom_col
and theta = "y"
inside coord_polar
.
Color of the lines
The borders of the pie can be changed with the color
argument of the geom_bar
or geom_col
function.
Adding text
By default, the values are not displayed inside each slice. You can add them with geom_text
. Note that position_stack(vjust = 0.5)
will place the labels in the correct position.
Adding labels
An alternative to geom_text
is using geom_label
, which adds a border around the values. If you set this the legend will display the letter “a” inside the boxes, so we have overridden this behavior with show.legend = FALSE
.
Labels color
Note that you can change the color of the labels with color
.
Color palette
The default color palette can be changed with a predefined color palette, such as the scale_fill_brewer
or scale_fill_viridis_d
.
Custom colors
If you prefer setting your own colors you can make use of scale_fill_manual
and set the corresponding colors.
The default pie chart styling can be changed in ggplot2 making use of themes.
You can also remove the whole theme with theme_void
.
You can get a customized style customizing the theme
components. Note that you can create your custom theme if you want to reproduce the styling.
Legend title
The default legend title is the name of the categorical variable of the input data frame. Change it following the example below.
Legend labels
The labels of the lagend can also be modified. Use the labels
argument of scale_fill_discrete
or scale_fill_manual
.
Legend position
The legend can be placed in several positions with the legend.position
component of the theme
function. Possible placement values are "bottom"
, "left"
, "top"
and "right"
(default).
Remove the legend
If you prefer removing the legend set the position component to "none"
.
See also