Graphics Reference
In-Depth Information
Solution
Add geom_text() to your graph. It requires a mapping for x , y , and the text itself. By setting
vjust (the vertical justification), it is possible to move the text above or below the tops of the
bars, as shown in Figure 3-22 :
library(gcookbook) # For the data set
# Below the top
ggplot(cabbage_exp, aes(x = interaction(Date, Cultivar), y = Weight)) +
geom_bar(stat = "identity" ) +
geom_text(aes(label = Weight), vjust = 1.5 , colour = "white" )
# Above the top
ggplot(cabbage_exp, aes(x = interaction(Date, Cultivar), y = Weight)) +
geom_bar(stat = "identity" ) +
geom_text(aes(label = Weight), vjust = -0.2 )
Figure 3-22. Left: labels under the tops of bars; right: labels above bars
Notice that when the labels are placed atop the bars, they may be clipped. To remedy this, see
Changing the Order of Items on a Categorical Axis .
Discussion
In Figure 3-22 , the ycoordinates of the labels are centered at the top of each bar; by setting the
vertical justification ( vjust ), they appear below or above the bar tops. One drawback of this is
that when the label is above the top of the bar, it can go of the top of the plotting area. To fix
this, you can manually set the ylimits, or you can set the ypositions of the text abovethe bars
Search WWH ::




Custom Search