Evan Kroske
Evan Kroske

Reputation: 4554

How can I make my vertical labels fit within my plotting window?

I'm creating a histogram in R which displays the frequency of several events in a vector. Each event is represented by an integer in the range [1, 9]. I'm displaying the label for each count vertically below the chart. Here's the code:

hist(vector, axes = FALSE, breaks = chartBreaks)
axis(1, at = tickMarks, labels = eventTypes, las = 2, tick = FALSE) 

Unfortunately, the labels are too long, so they are cut off by the bottom of the window. How can I make them visible? Am I even using the right chart?

Upvotes: 20

Views: 54346

Answers (4)

John
John

Reputation: 23758

You might want to look at this post from Cross Validated

Upvotes: 0

Gavin Simpson
Gavin Simpson

Reputation: 174788

This doesn't sound like a job for a histogram - the event is not a continuous variable. A barplot or dotplot may be more suitable.

Some dummy data

set.seed(123)
vec <- sample(1:9, 100, replace = TRUE)
vec <- factor(vec, labels = paste("My long event name", 1:9))

A barplot is produced via the barplot() function - we provide it the counts of each event using the table() function for convenience. Here we need to rotate labels using las = 2 and create some extra space of the labels in the margin

## lots of extra space in the margin for side 1
op <- par(mar = c(10,4,4,2) + 0.1)
barplot(table(vec), las = 2)
par(op) ## reset

A dotplot is produced via function dotchart() and has the added convenience of sorting out the plot margins for us

dotchart(table(vec))

The dotplot has the advantage over the barplot of using much less ink to display the same information and focuses on the differences in counts across groups rather than the magnitudes of the counts.

Note how I've set the data up as a factor. This allows us to store the event labels as the labels for the factor - thus automating the labelling of the axes in the plots. It also is a natural way of storing data like I understand you to have.

Upvotes: 10

Greg
Greg

Reputation: 11764

Perhaps adding \n into your labels so they will wrap onto 2 lines? It's not optimal, but it may work.

Upvotes: 0

Dirk is no longer here
Dirk is no longer here

Reputation: 368181

Look at help(par), in particular fields mar (for the margin) and oma (for outer margin). It may be as simple as

par(mar=c(5,3,1,1))   # extra large bottom margin
hist(vector, axes = FALSE, breaks = chartBreaks)
axis(1, at = tickMarks, labels = eventTypes, las = 2, tick = FALSE) 

Upvotes: 11

Related Questions