R - ggplot - лаборатории (subtitle= и caption=) не работают

У меня проблема с правильным добавлением текстовых элементов на график в некоторых моих диаграммах. Я использую ggplot2 и + labs(...), но в мой график включены только некоторые элементы.

Это один из графиков:

colnames(dane.trust)[1] = "Country" #GEO.INDIC_WB
w5 <- ggplot(dane.trust, aes(x = reorder(Country, Trust.Index), y = Trust.Index, fill=Country)) + scale_fill_brewer(palette = "Set2")
w5 + geom_bar(stat="identity") + #guides(fill=FALSE)  +
geom_text(data=dane.trust[,c(1,6)], label = round(Trust.Index, digits = 2),vjust = -0.5, aes(inherit.aes = TRUE, fontface=2)) +
theme_bw() + labs(x="", y="Average Rating (0-10)", title = "Overall trust levels", subtitle="Index of trust to political and legal systems, police and others") +
theme(title = element_text(face = "bold", color = "black"), axis.title = element_text(face = "bold", color = "black"), panel.grid.major.x = element_blank())

Заголовок, x.label и y.label работают нормально, но я не вижу ни подзаголовка, ни подписи.

Ошибки нет, просто тех элементов нет.

Кто-нибудь знает, в чем может быть проблема?

EDIT1: вот вывод > dput(dane.trust)

structure(list(Country = structure(1:5, .Label = c("Bulgaria", 
"Hungary", "Poland", "Romania", "Slovakia"), class = "factor"), 
Trust.in.the.political.system = c(2.6, 4.5, 3.5, 4.8, 3.5
), Trust.in.the.police = c(3.6, 5.7, 5.2, 6.4, 4.4), Trust.in.others = c(4.2, 
5.3, 6, 6.4, 5.8), Trust.in.the.legal.system = c(3, 5.1, 
4.2, 5.8, 3.6), Trust.Index = c(3.35, 5.15, 4.725, 5.85, 
4.325)), .Names = c("Country", "Trust.in.the.political.system", 
"Trust.in.the.police", "Trust.in.others", "Trust.in.the.legal.system", 
"Trust.Index"), row.names = c(NA, -5L), class = "data.frame")

EDIT2: я только что проверил свой исходный код на другом компьютере, он сработал. Что может быть причиной этого?

Хорошо, после переустановки R и RStudio все заработало, всем спасибо за ответы :).


person Slynny    schedule 23.11.2018    source источник
comment
Это не воспроизводимый пример. Было бы полезно, если бы вы могли предоставить вывод dput(dane.trust) в блоке кода.   -  person hrbrmstr    schedule 23.11.2018
comment
Какую версию ggplot2 вы используете?   -  person JdeMello    schedule 23.11.2018
comment
@JdeMello версия: ggplot 2_2.1.0   -  person Slynny    schedule 23.11.2018
comment
@Slynny замени geom_text(...) на geom_text(vjust = -0.5, aes(fontface=2), label = dane.trust$Trust.Index). Аргумент label в geom_text() может оценивать только Trust.Index внутри аргумента aes(). Вам нужно указать вектор в аргументе label = ... вне aes(). Таким образом, вы можете сделать либо geom_text(label = dane.trust$Trust.Index, ...), либо geom_text(data = dane.trust[, c(1, 6)], ..., aes(label = Trust.Index)).   -  person JdeMello    schedule 23.11.2018


Ответы (2)


Это должно сделать

w5 <- ggplot(dane.trust, aes(x = reorder(Country, Trust.Index), y = Trust.Index, fill=Country)) + scale_fill_brewer(palette = "Set2")
w5 + geom_bar(stat="identity") + #guides(fill=FALSE)  +
  geom_text(vjust = -0.5, aes(fontface=2), label = dane.trust$Trust.Index) +
  theme_bw() + labs(x="", y="Average Rating (0-10)", title = "Overall trust levels", subtitle="Index of trust to political and legal systems, police and others") +
  theme(title = element_text(face = "bold", color = "black"), axis.title = element_text(face = "bold", color = "black"), panel.grid.major.x = element_blank())

Аргумент label в geom_text() может оценивать Trust.Index только внутри aes(), когда предоставляется data. Вы либо указываете вектор в label = ... снаружи aes(), либо вставляете label =... внутрь aes() вот так geom_text(data = dane.trust[, c(1, 6)], ..., aes(label = Trust.Index))

person JdeMello    schedule 23.11.2018
comment
Нет-нет, у меня нет проблем с метками значений. Проблема в том, что из всех вещей в строке labs(x="", y="Average Rating (0-10)", title = "Overall trust levels", subtitle="Index of trust to political and legal systems, police and others") видны только некоторые. Здесь часть subtitle="Index of trust to political and legal systems, police and others не отображается на выходном графике. - person Slynny; 23.11.2018
comment
мой код создал тот же график, что и другой ответ. Когда я попытался запустить ваш код, я не смог создать график из-за проблемы в geom_text(), отсюда и мой ответ. Я предлагаю удалить ggplot2 и установить его снова. - person JdeMello; 24.11.2018

Ваша ошибка возникает при неправильном вызове geom_text() fixit, все остальное отображается нормально.

library(ggplot2)

dane.trust <- structure(list(Country = structure(1:5, .Label = c("Bulgaria", 
                                                                 "Hungary", "Poland", "Romania", "Slovakia"), class = "factor"), 
                             Trust.in.the.political.system = c(2.6, 4.5, 3.5, 4.8, 3.5
                             ), Trust.in.the.police = c(3.6, 5.7, 5.2, 6.4, 4.4), Trust.in.others = c(4.2, 
                                                                                                      5.3, 6, 6.4, 5.8), Trust.in.the.legal.system = c(3, 5.1, 
                                                                                                                                                       4.2, 5.8, 3.6), Trust.Index = c(3.35, 5.15, 4.725, 5.85, 
                                                                                                                                                                                       4.325)), .Names = c("Country", "Trust.in.the.political.system", 
                                                                                                                                                                                                           "Trust.in.the.police", "Trust.in.others", "Trust.in.the.legal.system", 
                                                                                                                                                                                                           "Trust.Index"), row.names = c(NA, -5L), class = "data.frame")

colnames(dane.trust)[1] = "Country" #GEO.INDIC_WB

w5 <- ggplot(dane.trust, aes(x = reorder(Country, Trust.Index), y = Trust.Index, fill=Country)) + scale_fill_brewer(palette = "Set2")

w5 + geom_bar(stat = "identity") +
  geom_text(aes(label = round(Trust.Index, digits = 2)), vjust = -0.5) +
  theme_bw() +
  labs(
    x = "",
    y = "Average Rating (0-10)",
    title = "Overall trust levels",
    subtitle = "Index of trust to political and legal systems, police and others"
  ) +
  theme(
    title = element_text(face = "bold", color = "black"),
    axis.title = element_text(face = "bold", color = "black"),
    panel.grid.major.x = element_blank()
  )

Создана 23 ноября 2018 г. с помощью пакета reprex (v0.2.1)

person Jake Kaupp    schedule 23.11.2018
comment
К сожалению, этот код у меня тоже не работает, он дает точно такой же результат, как и раньше. - person Slynny; 24.11.2018
comment
Я только что проверил свой исходный код на другом компьютере, он сработал. Вы не знаете, в чем может быть проблема на моем ПК? - person Slynny; 24.11.2018
comment
Это не ваш компьютер. Иногда новые установки и новые сеансы устраняют основные проблемы, сохраняющиеся в вашей среде. - person Jake Kaupp; 24.11.2018
comment
Да, я решил переустановить RStudio и R, и это сработало. Хотя столько времени потеряно. В любом случае, спасибо за помощь :) - person Slynny; 24.11.2018