How to properly fit a graph in rmarkdown editor and knitted html document?

I am creating some plots that have some alignment issues in rmarkdown editor & html documents.

Graph is not aligning in center even on using fig.align='center' and its also cutting out at edges (PS in attached image: names of the countries have been cut out on left side).

How can I have the chart scrollable on x axis rather than cutting out or scaling down as that makes it unreadable.

For example charts on this webpage is scrollable rather than scaled down: https://cran.r-project.org/web/packages/gapminder/README.html

Use of chunk settings is shown in below image:

I have also used these chunk settings:

knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, dpi = 300, cache = FALSE, attr.output='style="max-height: 300px;"')

Issue of country names getting cut out is shown in below image

Code for Ref.

library(tidyverse)

gapminder <- read.csv("https://raw.githubusercontent.com/swcarpentry/r-novice-gapminder/gh-pages/_episodes_rmd/data/gapminder-FiveYearData.csv")

# Converting char to factors
gapminder <- gapminder %>% mutate_if(is.character, as.factor)

gapminder_gdpPercap_diff  <- gapminder %>% 
                              filter(year %in% c(1952,2007)) %>% 
                              
                              # filter(country %in% c("India","Vietnam")) %>% 
                              
                              arrange(country, year) %>% 
                              
                              group_by(country) %>% 
                              
                              mutate(gdpPercap_diff = gdpPercap[2] - gdpPercap[1],
                                     max_pop = max(pop)) %>% 
                              
                              ungroup() %>% 
                              
                              arrange(gdpPercap_diff) %>% 
                              
                              filter(max_pop > 30000000) %>% 
                              
                              mutate(country = droplevels(country)) %>% 
                              select(country, year, continent, gdpPercap, gdpPercap_diff)

gapminder_gdpPercap_diff %>% 
  mutate(country = fct_inorder(country)) %>% 
  
  group_by(country) %>% 
  
  mutate(max_gdpPercap = max(gdpPercap),
         min_gdpPercap = min(gdpPercap)) %>% 
  
  ungroup() %>% 

 # plotting begins
  ggplot() +
  geom_segment(aes(x = min_gdpPercap, xend = max_gdpPercap,
                   y = country, yend = country,
                   col = continent), alpha = 0.5, size = 7) +
  
  geom_point(aes(x = gdpPercap, y = country, col = continent), size = 8, alpha = .8) +
  
  geom_text(aes(x = min_gdpPercap + 10, y = country,
                label = paste(country, round(min_gdpPercap))),
            col = "grey50", hjust = "right") +
  
  geom_text(aes(x = max_gdpPercap - 8.0, y = country,
                label = round(max_gdpPercap)),
            col = "grey50", hjust = "left") +
  
  # scale_x_continuous(limits = c(20,85)) +
  
  scale_color_brewer(palette = "Pastel2") +
  
  labs(title = "Change in GDP Per Capita",
       subtitle = "Between years 1952 and 2007",
       col = "Continent") +
  
  # background & theme settings
  theme_classic() +
  
  theme(legend.position = "top", 
        axis.line = element_blank(),
        axis.ticks = element_blank(),
        axis.text = element_blank()
        )

Please correct reprex

Error: Problem with mutate() input country.
x no applicable method for 'droplevels' applied to an object of class "character"
:information_source: Input country is droplevels(country).>

@technocrat, thanks for letting me know. It was because of a missing line of code of converting char to factors which I have updated now: gapminder <- gapminder %>% mutate_if(is.character, as.factor)

1 Like

I suggest adjusting theming before taking up html placement. A 6000 × 3144 pixels plot from console shows that the left margin cannot be fixed in html

I have tried adjusting them with fig.width = 12 chunk option and scale_x_continuous(limits = c(-1000,45000)) in the plot code which fix the margins but that shrinks the chart and all the labels becomes unreadable. I would rather prefer to have big size plot that can be scrolled and remains readable.

Below is the image for scale_x_continuous(limits = c(-1000,35000))

Look closely at the attached image in my answer. No adjustment in the HTML rendering is going to save the last line of the plot, even scaling the image (preserving the aspect ratio)

Yes, so may be making output results scroll able will fit the chart from end to end without loosing information but I am not sure how to do that.

I was able to make scroll able output for text outputs (adjusting height of outputs) using below code from this link but it doesn't make plot outputs as scroll able : https://bookdown.org/yihui/rmarkdown-cookbook/html-scroll.html#html-scroll

.scroll-100 {
  max-height: 100px;
  overflow-y: auto;
  background-color: inherit;
}

Don’t make me say it, Jon Snow.

Are you OK with the image produced by your code? You aren’t interested in fixing it first?

@technocrat, I am a newbie in programing specially R.

I am not sure how to produce a clean graph in this case which can be readable to any person without loosing information.
A clean readable graph is all I want and I have put in best of my knowledge and whatever I have found from google.

Beyond this I don't know how to fix it as I have very limited understanding of R and that's why I have posted here if I can get any help with options or settings or code otherwise I will skip this .

Apologies for the snark. I mistook your level of expertise.

One approach to fixing the underlying plot is to go portrait by adjusting the aspect with coord_fixed and removing country from the paste. Try rendering with this and adjust figure width, and we can go on to slider from there, if needed.

library(tidyverse)

gapminder <- read.csv("https://raw.githubusercontent.com/swcarpentry/r-novice-gapminder/gh-pages/_episodes_rmd/data/gapminder-FiveYearData.csv") -> gminder

# Converting char to factors
gapminder <- gminder %>% mutate_if(is.character, as.factor)

gapminder_gdpPercap_diff <- gapminder %>%
  filter(year %in% c(1952, 2007)) %>%
  
  # filter(country %in% c("India","Vietnam")) %>%
  
  arrange(country, year) %>%
  group_by(country) %>%
  mutate(
    gdpPercap_diff = gdpPercap[2] - gdpPercap[1],
    max_pop = max(pop)
  ) %>%
  ungroup() %>%
  arrange(gdpPercap_diff) %>%
  filter(max_pop > 30000000) %>%
  mutate(country = droplevels(country)) %>%
  select(country, year, continent, gdpPercap, gdpPercap_diff)

gapminder_gdpPercap_diff %>%
  mutate(country = fct_inorder(country)) %>%
  group_by(country) %>%
  mutate(
    max_gdpPercap = max(gdpPercap),
    min_gdpPercap = min(gdpPercap)
  ) %>%
  ungroup() %>%
  
  # plotting begins
  ggplot() +
  geom_segment(aes(
    x = min_gdpPercap, xend = max_gdpPercap,
    y = country, yend = country,
    col = continent
  ), alpha = 0.5, size = 7) +
  geom_point(aes(x = gdpPercap, y = country, col = continent), size = 8, alpha = .8) +
  geom_text(aes(
    x = min_gdpPercap + 10, y = country,
    # remove country here <=======================================
    label = paste(round(min_gdpPercap))
  ),
  col = "grey50", hjust = "right"
  ) +
  geom_text(aes(
    x = max_gdpPercap - 8.0, y = country,
    label = round(max_gdpPercap)
  ),
  col = "grey50", hjust = "left"
  ) +
  
  # scale_x_continuous(limits = c(20,85)) +
  
  scale_color_brewer(palette = "Pastel2") +
  labs(
    title = "Change in GDP Per Capita",
    subtitle = "Between years 1952 and 2007",
    col = "Continent"
  ) +
 
  # background & theme settings
  theme_classic() +
  theme(
    legend.position = "top",
    axis.line = element_blank(),
    axis.ticks = element_blank(),
    axis.text = element_blank() +
  # adjust aspect here              <===========================
    coord_fixed(ratio = .5) 
  ) -> the_plot
the_plot

Created on 2020-10-01 by the reprex package (v0.3.0.9001)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.