X轴标签在R小节图中未正确对齐

时间:2019-01-28 10:13:12

标签: r plot bar-chart

我有data.table数据来创建堆积图并使用以下代码进行分组:

causesDf <- causesDf[, c('Type', 'Gender', 'Total')]
causesSort <- causesDf[, lapply(.SD, sum), 
                       by=list(causesDf$Type, causesDf$Gender)]

数据将如下所示:

                           causesDf causesDf.1  Total

 1:                        Illness (Aids/STD)     Female   2892
 2:                 Change in Economic Status     Female   4235
 3:   Cancellation/Non-Settlement of Marriage     Female   6126       
 4:                           Family Problems     Female 133181
 5:                        Illness (Aids/STD)       Male   5831
 6:                 Change in Economic Status       Male  31175
 7:    Cancellation/Non-Settlement of Marriage       Male   5170

以此类推。

我正在尝试制作如下的barplot:

barpos <- barplot(sort(causesSort$Total, decreasing=TRUE),
                  col=c("red","green"), xlab="", ylab="", 
                  horiz=FALSE, las=2)

legend("topright", c("Male","Female"), fill=c("red","green"))

end_point <- 0.2 + nrow(causesSort) + nrow(causesSort) - 0.1

text(seq(0.1, end_point, by=1), par("usr")[3] - 30,
     srt=60, adj= 1, xpd=TRUE,
     labels=paste(causesSort$causesDf), cex=0.65)

但是X标签不能正确对齐,我错过了什么吗?

enter image description here

预期的输出如下:

enter image description here

已编辑:

原因排序

structure(list(causesDf = c("Illness (Aids/STD)", "Change in Economic Status", 
"Cancellation/Non-Settlement of Marriage", "Physical Abuse (Rape/Incest Etc.)", 
"Dowry Dispute", "Family Problems", "Ideological Causes/Hero Worshipping", 
"Other Prolonged Illness", "Property Dispute", "Fall in Social Reputation", 
"Illegitimate Pregnancy", "Failure in Examination", "Insanity/Mental Illness", 
"Love Affairs", "Professional/Career Problem", "Divorce", "Drug Abuse/Addiction", 
"Not having Children(Barrenness/Impotency", "Causes Not known", 
"Unemployment", "Poverty", "Death of Dear Person", "Cancer", 
"Suspected/Illicit Relation", "Paralysis", "Property Dispute", 
"Unemployment", "Poverty", "Family Problems", "Illness (Aids/STD)", 
"Drug Abuse/Addiction", "Other Prolonged Illness", "Death of Dear Person", 
"Causes Not known", "Cancer", "Not having Children(Barrenness/Impotency", 
"Cancellation/Non-Settlement of Marriage", "Paralysis", "Physical Abuse (Rape/Incest Etc.)", 
"Professional/Career Problem", "Love Affairs", "Fall in Social Reputation", 
"Dowry Dispute", "Ideological Causes/Hero Worshipping", "Illegitimate Pregnancy", 
"Failure in Examination", "Change in Economic Status", "Insanity/Mental Illness", 
"Divorce", "Suspected/Illicit Relation", "Not having Children (Barrenness/Impotency", 
"Not having Children (Barrenness/Impotency"), causesDf.1 = c("Female", 
"Female", "Female", "Female", "Female", "Female", "Female", "Female", 
"Female", "Female", "Female", "Female", "Female", "Female", "Female", 
"Female", "Female", "Female", "Female", "Female", "Female", "Female", 
"Female", "Female", "Female", "Male", "Male", "Male", "Male", 
"Male", "Male", "Male", "Male", "Male", "Male", "Male", "Male", 
"Male", "Male", "Male", "Male", "Male", "Male", "Male", "Male", 
"Male", "Male", "Male", "Male", "Male", "Female", "Male"), Total = c(2892, 
4235, 6126, 2662, 31206, 133181, 776, 69072, 4601, 4697, 2391, 
12054, 33352, 21339, 1596, 2535, 1205, 5523, 148134, 3748, 7905, 
4707, 2878, 8093, 2284, 14051, 23617, 24779, 208771, 5831, 28841, 
125493, 5614, 304985, 6180, 2299, 5170, 5002, 1330, 10958, 23700, 
8767, 764, 1342, 103, 14951, 31175, 60877, 1598, 6818, 544, 222
)), row.names = c(NA, -52L), class = c("data.table", "data.frame"
)
# , .internal.selfref = <pointer: 0x00000000098d1ef0>  # seems not to work
)

2 个答案:

答案 0 :(得分:2)

如果您不依赖于45°旋转(这有点棘手),则可以使用此解决方案。

首先,我们需要按性别重塑数据。

Content-Type

然后,我们从text/xml; charset=utf-8列中生成行名,并将其删除。

library(reshape2)
df2 <- dcast(causesSort, ... ~ causesDf.1 , value.var="Total")

然后我们按一列对数据进行排序,例如由type

rownames(df2) <- df2[, 1]
df2 <- df2[, -1]

标签是行名。

Female

但是,由于它们很长(并且对读者不利!),我们可能不得不考虑较短的那些。一种解决方法是将它们缩短一些。

df2 <- df2[order(-df2$Female), ]

现在我们可以应用# labs <- rownames(df2)

labs <- substr(sapply(strsplit(rownames(df2), " "), 
                      function(x) x[1]), 1, 8)

barplot()为我们提供了一个条形位置矩阵,因为我们有一个分组图,因此需要列均值。我们可以用它来绘制轴。

pos <- barplot(t(df2), beside=TRUE, xaxt="n",
               col=c("#3C6688", "#45A778"), border="white")

结果 enter image description here

答案 1 :(得分:1)

这是ggplot2解决方案。这样可以更好地控制最终输出

library(dplyr)
library(ggplot2)

#Rename columns names
names(causesDf) <- c('Type', 'Gender', 'Total')

#sort male before females
causesDf$Gender<-factor(causesDf$Gender, levels=c("Male", "Female"), ordered=TRUE)

#sort types by total sum and sort in decreasing order
sorted<-causesDf %>% group_by(Type) %>% summarize(gtotal=sum(Total)) %>% arrange(desc(gtotal))
causesDf$Type<-factor(causesDf$Type, levels=sorted$Type, ordered=TRUE)


#plot graph
g<-ggplot(causesDf, aes(x=Type, y=Total, group=Gender, fill=Gender)) + 
  geom_col(position = "dodge") +
  theme(axis.text.x = element_text(angle = 45, hjust=1)) +
  scale_fill_manual(values = alpha(c("blue", "green"), .5))
print(g)

enter image description here