我正在绘制一些数据,我需要创建许多箱形图。不同的类别是月份,由于我需要按顺序显示它们,而不是按字母顺序显示,因此我用
将日期转换为一个因子。dd.tot$month <- factor(format(dd.tot$month, "%b"),
levels=format(ISOdate(2000, 1:12, 1), "%b"))
由于我的系统语言(以及该语言的母语)是意大利语,因此dd.tot数据框中的month列是意大利语。 但是我需要他们使用英文缩写(本文全为英文,这将是意大利语的唯一组成部分)。 我试图用不同的缩写创建一个新的向量,以使用
mymonths <- c("Jan","Feb","Mar",
"Apr","May","Jun",
"Jul","Aug","Sep",
"Oct","Nov","Dec")
dd.tot$month <- mymonths[ dd.tot$month ]
但是当我用ggplot
绘制时,它们以字母顺序显示。如何翻译它们并将它们作为因素?
答案 0 :(得分:2)
这是一些数据的示例,我们在其中解决了两个问题。
# My data
df <- data.frame(mymonths = c("Jan","Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),
somevalue = c(1:12))
# Plotting
library(ggplot2)
ggplot(df, aes(mymonths, somevalue)) + geom_bar(stat="identity")
# Fixing order
df$mymonths <- factor(df$mymonths, levels = c("Jan","Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"))
# Plotting
ggplot(df, aes(mymonths, somevalue)) + geom_bar(stat="identity")
# Fixing labels
df$mymonths <- factor(df$mymonths,
levels = c("Jan","Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),
labels = c("Jan_cool","Feb_cool", "Mar_cool","Apr_cool","May_cool","Jun_cool","Jul_cool","Aug_cool","Sep_cool","Oct_cool","Nov_cool","Dec_cool"))
# Plotting
ggplot(df, aes(mymonths, somevalue)) + geom_bar(stat="identity")
答案 1 :(得分:0)
您可以将本地语言设置为英语。只需输入:
Sys.setlocale("LC_TIME", "English")
然后,您不必翻译它们,就可以像这样订购它们:
mymonths <- format(seq.Date(from = as.Date("2018-01-01"), to = as.Date("2018-12-01"), by = "m"), "%b")
dd.tot$month <- factor(format(dd.tot$month, %b), levels = mymonths)
如果您想将其恢复为意大利语,只需键入
Sys.setlocale("LC_TIME", "Italian")