[英]Changing x-axis labels in ggplot
I have a bar plot that has 12 x values. 我有一个具有12 x值的条形图。 Using this code I get the plot I want except for the x-axis labels.
使用此代码,除了x轴标签外,我还可以获得所需的绘图。
p <- ggplot(data=df.mean, aes(x=stock_name, y=invest_amnt, fill=trend_id)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=invest_amnt-ic, ymax=invest_amnt+ic), width=.2,
position=position_dodge(.9))
p + scale_fill_brewer(palette="Paired") + theme_minimal() +
theme(text = element_text(size=12, hjust = 0.5, family="Times")) +
theme_stata() + scale_color_stata()
Instead of displaying all 12 values on the x-axis I want to determine the labels by myself and only display 4. 我不想在x轴上显示所有12个值,而是由我自己确定标签,只显示4个。
I adjusted the code like this 我这样调整了代码
p <- ggplot(data=df.mean, aes(x=stock_name, y=invest_amnt, fill=trend_id)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=invest_amnt-ic, ymax=invest_amnt+ic), width=.2,
position=position_dodge(.9)) +
scale_x_discrete( labels=c("UP\nDOWN", "DOWN\nUP", "STRAIGHT\nGAIN", "STRAIGHT\nLOSS")) +
scale_fill_discrete(name = "Trend", labels = c("negative", "flat", "positive"))
p + scale_fill_brewer(palette="Paired") + theme_minimal() +
theme(text = element_text(size=12, hjust = 0.5, family="Times")) +
theme_stata() + scale_color_stata()
Unfortunately, I get my 4 labels but also 8 NAs. 不幸的是,我得到了4个标签,但还有8个NA。 I would like my 4 labels to be evenly spread on my x-axis.
我希望我的4个标签均匀地分布在我的x轴上。 Since my labels are factors I do not know how to apply
break
here. 由于标签是影响因素,因此我不知道如何在此处应用
break
。
I've generated some sample data...hope I've understood the situation correctly. 我已经生成了一些示例数据...希望我正确理解了这种情况。 This seems to work, ie inserts breaks at the specified locations on a barplot, using the specified labels.
这似乎可行,即使用指定的标签在小节上的指定位置插入中断。
library(tidyverse)
df <- tribble(~x, ~y,
'cat',10,
'dog', 20,
'rabbit', 30,
'fox', 30)
df <- df %>%
mutate(x = factor(x))
df %>% ggplot(aes(x,y))+
geom_bar(stat = 'identity') +
scale_x_discrete(breaks = c('cat','fox'), labels = c('pig', 'hen'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.