r - 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):
If I create a larger plot (like fill my screen with it) I get this:
(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!
解决方案
请注意theme_set
和theme_tufte
是ggplot2
特定功能。
使用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")
推荐阅读
- xcode - 在 iOS 模拟器上 React Native `RuntimeError: abort(Error: xcrun exited with non-zero code: 2`
- python - 如何向熊猫数据框添加条件计数器
- python - Opencv真型字体反转和拆分阿拉伯字符
- c++ - 在命名空间内定义一个类(在命名空间内?)
- sql-server - 递增计数器后的 SQL Server 回滚行为
- java - 使用 Antlr 读取和解析 PIPE
- javascript - 如何在wix网站中添加子子菜单
- c# - 根据表单内部的控件设置 MinimumSize
- odoo - 仅为特定组创建按钮
- database - 处理来自数据库和列表的数据的更好方法