在R中绘制点图
下面是我的数据集在R中绘制点图,r,plot,ggplot2,R,Plot,Ggplot2,下面是我的数据集 dput(test21) structure(list(Freq = c(9L, 7L, 7L, 4L), MonthAbb = c("Jan", "Feb", "Mar", "Apr")), .Names = c("Freq", "MonthAbb"), row.names = c(NA, -4L), class = "data.frame") 我知道如何使用这些数据创建条形图,但是,我对创建下面这样的点图感兴趣 实现这一点的一种方法如下 a1 = seq(1, 9,
dput(test21)
structure(list(Freq = c(9L, 7L, 7L, 4L), MonthAbb = c("Jan",
"Feb", "Mar", "Apr")), .Names = c("Freq", "MonthAbb"), row.names = c(NA,
-4L), class = "data.frame")
我知道如何使用这些数据创建条形图,但是,我对创建下面这样的点图感兴趣
实现这一点的一种方法如下
a1 = seq(1, 9, length.out = 9)
a2 = rep(LETTERS[1], 9)
a = cbind(a1,a2)
b1 = seq(1, 7, length.out = 7)
b2 = rep(LETTERS[2], 7)
b = cbind(b1,b2)
c1 = seq(1, 7, length.out = 7)
c2 = rep(LETTERS[3], 7)
c= cbind(c1,c2)
d1 = seq(1, 4, length.out = 4)
d2 = rep(LETTERS[4], 4)
d= cbind(d1,d2)
test21a = as.data.frame(rbind(a,b,c,d))
test21a$a1 = as.numeric(test21a$a1)
ggplot(data = test21a, aes(x=a2, y=a1, color = a2)) + geom_point()
但这是非常低效的,我正在手动创建一个数字序列。有兴趣了解是否有更好更有效的方法进行此操作。您可以重新构造数据,以创建与堆叠点等效的“条形图”
# Restructure data
dat = data.frame(MonthAbb = rep(test21$MonthAbb, test21$Freq),
Count = sequence(test21$Freq))
dat$MonthAbb = factor(dat$MonthAbb, levels=month.abb)
ggplot(dat, aes(MonthAbb, Count - 0.5, fill=MonthAbb)) +
geom_point(size=6, pch=21, show.legend=FALSE) +
#geom_text(data=test21, aes(label=Freq, y=Freq), vjust=-0.5) + # To put labels above markers
geom_text(data=test21, aes(label=Freq, y=Freq - 0.5)) + # To put labels inside topmost markers
scale_y_continuous(limits=c(0,max(dat$Count)), breaks=0:max(dat$Count)) +
theme_bw() +
labs(x="Month", y="Frequency")
然而,在我看来,线条图在这里更有效:
test21$MonthAbb = factor(test21$MonthAbb, levels=month.abb)
ggplot(test21, aes(MonthAbb, Freq)) +
geom_line(aes(group=1)) +
geom_point() +
scale_y_continuous(limits=c(0, max(test21$Freq)), breaks=0:max(test21$Freq)) +
theme_bw() +
labs(x="Month", y="Frequency")
它必须是那样的还是像点图(test21$Freq,labels=test21$MonthAbb,pch=20,col=c('red','blue','green','grey'))做什么?@steveb,我可以用
ggplot(data=test21,aes(x=MonthAbb,y=Freq))+geom_point()做你提到的事情
但这不是我的想法。我同意线形图,但y轴上的词频有点误导。我应该把它改成更有意义的东西。但你的解决方案是完美的。正是我想要的,谢谢EIPI10我想你可以把定义Count
的表达式简化为sequence(test21$Freq)
谢谢你指出@alistaire。我已经更新了我的答案。我记得在雾蒙蒙的过去的某个地方了解到了序列的存在,但以前从未使用过它。@eipi10,alistaire一个装饰性的问题,我如何在每个虚线的顶部添加标签,9,7,7,4(最大值)…?你可以使用geom_text
。请参阅更新的答案。