我想使用因子和方面来控制图形的显示。
我已经咨询了许多来源以获得我所处的位置,但我不能将这些信息拼凑起来以解决我生产的图表的最终问题。
我特别想完成:
示例数据和代码如下:
##### !!!!! graphing with factors and facets
library(ggplot2)
lm <- read.table(header=TRUE, text="
country| medal.type | count | member
South Korea | gold |13 | 0
Italy | gold |8 | 1
France | gold |11 | 1
Australia | gold |7 | 0
Japan | gold |7 | 0
Germany | gold |11 | 1
Great Britain & N. Ireland | gold |29 | 1
Russian Federation | gold |24 | 0
China | gold |38 | 0
United States | gold |46 | 0
South Korea | silver |8 | 0
Italy | silver |9 | 1
France | silver |11 | 1
Australia | silver |16 | 0
Japan | silver |14 | 0
Germany | silver |19 | 1
Great Britain & N. Ireland | silver |17 | 1
Russian Federation | silver |26 | 0
China | silver |27 | 0
United States | silver |29 | 0
South Korea | bronze |7 | 0
Italy | bronze |11 | 1
France | bronze |12 | 1
Australia | bronze |12 | 0
Japan | bronze |17 | 0
Germany | bronze |14 | 1
Great Britain & N. Ireland | bronze |19 | 1
Russian Federation | bronze |32 | 0
China | bronze |23 | 0
United States | bronze |29 | 0
XXXXXXX | bronze |12 | 0
", sep="|" )
lm$medal.type_f <- factor(lm$medal.type, labels= c("gold","silver","bronze"))
lm$country_l <- with(lm, paste(country, medal.type, sep = "_"))
lm$member_f <- factor(lm$member , labels = c("Not EU" , "EU"))
# Make every country unique
lm$country_l <- with(lm, paste(country, medal.type, sep = "_"))
dev.new(width=12, height=8)
p <- ggplot(lm, aes(x=count , y=country , group=member_f ) )
p + geom_point(size=3, aes( shape=factor(member_f))) +
scale_shape_manual(values=c(1,19)) +
scale_size_manual(values=c(3,3)) +
scale_fill_manual(name="European Union\n Membership") +
facet_grid(medal.type_f ~., scales="free" ) + geom_vline(xintercept=mean(lm$count), color="red") +
xlab("Count of Medals") +
scale_y_discrete("Country", breaks = lm$country, label = lm$country)
##### !!!!! end of program
我想在一个方面内从最高到最低的顺序订购奖牌,并更改图例标题。我想用一个因子表明一个国家是否是欧盟成员国,所以我用不同的符号来表示。我使用scale_fill_manual
的尝试失败了。
为我制作的图表是:
我咨询过的一些参考文献如下:
答案 0 :(得分:1)
您评论中包含的链接符合您的需求。您需要重新排序y轴并使用country_l
而不是country
设置中断。首先,你的代码中存在一个错误,使铜牌和银牌组交换(所以银牌数据在标有铜牌的方面,反之亦然)。
您可以像这样创建medal.type_f
列:
lm$medal.type_f <- factor(lm$medal.type, levels(lm$medal.type)[c(1, 3, 2)])
然后创建你的情节:
p <- ggplot(lm, aes(x = count, y = reorder(country_l, count), group = member_f))
p + geom_point(size=3, aes(shape=factor(member_f))) +
scale_shape_manual(values=c(1,19)) +
scale_size_manual(values=c(3,3)) +
scale_fill_manual(name="European Union\n Membership") +
facet_grid(medal.type_f ~., scales="free" ) +
geom_vline(xintercept=mean(lm$count), color="red") +
xlab("Count of Medals") +
scale_y_discrete("Country", breaks = lm$country_l, label = lm$country) +
# To rename the legend:
labs(shape = "EU membership")