ggplot:更好地呈现barplot

时间:2013-11-12 16:59:14

标签: r ggplot2

我有一个小数据帧DF,它由两列X = Type,Y = Cost组成。想要绘制每种类型的条形图及其成本。我已设法做到这一点,但是,我正在寻求在barplot中更好的演示。我认为有三个问题可以满足我的要求:

1)由于每种类型的X轴文本很长,我用45度制作它们。我试过缩写,这是不可读的!

2)我试图在ggplot中使用填充图案/纹理而不是颜色,Hadley认为这是不可能的:fill patterns

在黑/白打印的情况下,有没有办法让图表可读?

3)我想知道是否有办法专注于其中一个“类型”类别,即使其大胆和特殊的颜色吸引眼球到这种特殊类型。例如,我想让“其他”结果看起来与其他结果不同。

我尝试了自己的想法,然而,我完全乐于重新设计图表。任何建议

这是数据 - 我使用了dput命令:

structure(list(Type = structure(c(6L, 8L, 7L, 9L, 10L, 15L, 11L, 
17L, 3L, 16L, 5L, 19L, 4L, 14L, 2L, 18L, 13L, 1L, 12L), .Label = c("Backup Hardware ", 
"data or network control", "Email exchange server/policy", "Instant messaging control", 
"Login/system administrators/privilage", "Machine A", "Machine A with Software and   Camera", 
 "Machine A without Software", "Machine B", "Machine B without RAM and CD ROM", 
"Managment analyses software ", "Other", "Password and security", 
"public web application availability", "Software for backup", 
"System access by employees ", "Telecom and Harware", "Web site update", 
"wireless network access ponits"), class = "factor"), Cost = structure(c(4L, 
3L, 15L, 13L, 11L, 7L, 2L, 1L, 19L, 16L, 14L, 12L, 10L, 9L, 8L, 
6L, 5L, 17L, 18L), .Label = c("$1,292,312", "$1,888,810", "$11,117,200", 
"$14,391,580", "$161,210", "$182,500", "$2,145,900", "$250,000", 
"$270,500", "$298,810", "$3,452,010", "$449,001", "$6,034,000", 
"$621,710", "$7,642,660", "$700,000", "$85,100", "$885,000", 
"$923,700"), class = "factor")), .Names = c("Type", "Cost"), class = "data.frame",   row.names = c(NA, 
-19L))

这是我在R中的代码:

p<- ggplot(data = DF, aes(x=Type, y=Cost)) + 
 geom_bar(aes(fill=Type),stat="identity") + 
 geom_line()+
scale_x_discrete (name="Type")+
scale_y_discrete(name="Cost")+
theme(axis.text.x = element_text(colour="black",size=11,face="bold")) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))+
labs(fill=expression(paste("Type of study\n")))

print(p)

1 个答案:

答案 0 :(得分:4)

以下是您的情节的一些起点:

1)首先,将变量Cost从因子转换为数字,并将其命名为Cost2

DF$Cost2<-as.numeric(gsub("[^0-9]", "",DF$Cost))

2)使用scale_fill_manual()将您的绘图转换为灰度 - 此处所有条形均为灰色,但Other为黑色的条形除外。使用scale_y_continuous()将y轴值再次设为labels=dollar的美元(为此,您需要添加库scales)。要使x轴的Other标签变为粗体,而其他标准为正常,则应在face= theme()内提供参数axis.text.x=,其长度与级别数相同 - 所有1等级{2}为等级Other

library(scales)
ggplot(data = DF, aes(x=Type, y=Cost2)) + 
  geom_bar(aes(fill=Type),stat="identity",show_guide=FALSE) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1,
                                   face=(as.numeric(levels(DF$Type)=="Other") + 1)))+
  scale_y_continuous(labels=dollar)+
  scale_fill_manual(values=c("grey43","black")[as.numeric(levels(DF$Type)=="Other")+1])

enter image description here