0

These tick mark labels are too long and they are always shown in a single line. How could I have each one of them with a line break? That way, the image can be shown bigger and the x-axis tick mark labels would be visible.

library(ggplot2)

set.seed(69)

df <- data.frame(City= rep(c("Boston", "Caracas", "Madrid", "Tokio"), 4),
                 Val = sample(c("Yes", "No"), 16, TRUE),
                 Sport = rep(c("Ok let's see if today is the day, I am not sure we will be able to make it, Ok let's see if today is the day, I am not sure we will be able to make it","having a long tick is not helpful but sometimes it is unavoidable. So if that happens, what do we do?. having a long tick is not helpful but sometimes it is unavoidable. So if that happens, what do we do?", "this is a test to see what happens today in Stack Overflow", "here we go, let's make it happen today. I know this is long but I have to do it in order to better show my problem"), each = 4))

test <- ggplot(df, aes(City, Sport, fill = Val)) + 
  geom_tile(color = "#00000022") +
  scale_fill_manual(values = c("red", "forestgreen")) +
  coord_equal() +
  theme_bw() +
  labs(fill = "Sport popular?") +theme(axis.title.y = element_blank())


ggplotly (test)

enter image description here

user284437
  • 129
  • 5

1 Answers1

1

You can insert a line break after every comma and point and then explicitly set the size of the plot:

library(ggplot2)
library(dplyr)
library(purrr)

set.seed(69)

df <- data.frame(City= rep(c("Boston", "Caracas", "Madrid", "Tokio"), 4),
                 Val = sample(c("Yes", "No"), 16, TRUE),
                 Sport = rep(c("Ok let's see if today is the day, I am not sure we will be able to make it, Ok let's see if today is the day, I am not sure we will be able to make it","having a long tick is not helpful but sometimes it is unavoidable. So if that happens, what do we do?. having a long tick is not helpful but sometimes it is unavoidable. So if that happens, what do we do?", "this is a test to see what happens today in Stack Overflow", "here we go, let's make it happen today. I know this is long but I have to do it in order to better show my problem"), each = 4))

df <- df %>% 
  mutate(Sport = map_chr(Sport, ~paste0(strsplit(.x, "\\.|,")[[1]], collapse = "\n")))

test <- ggplot(df, aes(City, Sport, fill = Val)) + 
  geom_tile(color = "#00000022") +
  scale_fill_manual(values = c("red", "forestgreen")) +
  coord_equal() +
  theme_bw() +
  labs(fill = "Sport popular?") +theme(axis.title.y = element_blank())
test
ggsave("soplot.png", width = 20, height = 14, units = "cm")

Created on 2020-10-25 by the reprex package (v0.3.0)

When you use ggplotly, the default plot in the Viewer pane is probably too small, but if you enlarge it/zoom you see the plot correctly.

starja
  • 9,887
  • 1
  • 13
  • 28