首页 > 解决方案 > How do I prevent x labels from overlapping my bars in a barplot?

问题描述

Here is the code:

barplot(colMeans(sample_data, na.rm = TRUE),
    las = 1,
    main = "Main Title",
    xlab = "Variable",
    ylab = "How Characteristic",
    col = rainbow(20),
    cex.names = 0.9,
    horiz = FALSE)

A sample data set is available here:

https://github.com/akaEmma/public_data/blob/master/sample_data.csv Or you can type some of it in yourself. These are the variable names:

Love of Chocolate,Asian Knowledge,Stable Cleanliness,Love of People,Attention,Ethics,Aggression,Swimming,Style Points,Felinity

And here are some of the data that go with the names:

8.67    9   6.25    7.33    6.33    5       6.67    5   5.25
8       3   6       6.67    8       7       7.67    4.5 5.25
7.33    7.5 5.75    8.67    8.67    8       5.33    2.5 3
8       6.5 6       6.33    8.33    5.33    5.67    6   6.5
6       5.5 5.25    5.33    5       4.67    4       4   3.5
7.67    7   6       4.67    7.33    5.67    7.67    5   3.75
8.67    8   7.5     5.67    7.33    5       8.33    7   7.75

If I use the code above I get the following (ignore the periods; they aren't important):

Small Image that doesn't have good labels

If I create a larger plot (like fill my screen with it) I get this:

Now the labels overlap the bars.

(ignore the missing label; I accidentally left it off and it's supposed to be "Felinity," whatever that is)

This sort of bar chart is for a PowerPoint on a huge screen, so I can go very small with the labels.

Here is what I want: I want clean pretty labels, one per bar, and since this is a wish list, I want the labels to adjust their own sizes so that they are small enough to fit one per bar, and I want them to be at the right vertical point so that they do not overlap with the bars. Any ideas?

Go crazy. I want beautiful bar charts and I have to make a lot of them, so twiddling for each one is simply not an option. This has to work every time with data files of this type regardless of the length of the variable names.

Thanks!

标签: rpowerpoint

解决方案


请注意theme_settheme_tufteggplot2特定功能。

使用ggplot2你可以做这样的事情

df <- read.csv("https://raw.githubusercontent.com/akaEmma/public_data/master/sample_data.csv")

library(tidyverse)
library(ggthemes)
df %>%
    gather(key, value) %>%
    group_by(key) %>%
    summarise(mean.value = mean(value, na.rm = T)) %>%
    mutate(key = factor(key, levels = key[rev(order(mean.value))])) %>%
    ggplot(aes(key, mean.value, fill = as.numeric(key))) +
    geom_col() +
    theme_tufte() +
    scale_fill_gradientn(colours = rainbow(5), guide = F) +
    theme(axis.text.x = element_text(size = 6)) + 
    labs(x = "", y = "How characteristic")

在此处输入图像描述


推荐阅读