Ich möchte ein Balkendiagramm mit Monaten auf der X-Achse, zählt auf der Y-Achse und eine binäre Spalte (status
) als füllen. Hier ist der Code mit den Fehlern, Warnungen und der Handlung, die ich bekomme. Wie bekomme ich die richtige Handlung?R ggplot bar plot mit Monat auf X-Achse
library(ggplot2)
# to read in date correctly
setClass("myDate")
setAs("character",
"myDate",
function(from) as.Date(from, format = "%Y-%m-%d"))
csvData <- "id,dt,status
1,2015-12-03,1
2,2015-12-05,1
3,2015-12-05,0
4,2015-11-24,1
5,2015-10-17,0
6,2015-12-18,0
7,2016-06-30,0
8,2016-05-21,1
9,2016-03-31,0
10,2015-12-31,0"
tmp <- read.csv(textConnection(csvData),
colClasses = c("integer", "myDate", "factor"))
tmp$mon <- as.Date(cut(tmp$dt, breaks = "month"))
# The plot must have this time frame on the X-axis
dtLimits <- as.Date(c("2015-01-01", "2016-08-01"))
# This does not work
# since x is a factor here and scale uses date
ggplot(data = tmp, aes(x = as.factor(mon))) +
geom_bar(aes(fill = status)) +
scale_x_date(date_breaks = "1 month",
labels = date_format("%y/%m"),
limits = dtLimits)
# Error: Invalid input: date_trans works with objects of class Date only
# wrong plot with warning message
ggplot(data = tmp, aes(x = mon)) +
geom_bar(aes(fill = status)) +
scale_x_date(date_breaks = "1 month",
labels = date_format("%y/%m"),
limits = dtLimits) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
# Warning message:
# position_stack requires non-overlapping x intervals
Die Handlung von der letzten Anweisung erzeugt wird, wie folgt aus:
Der folgende Code die richtige Handlung erzeugt, aber nicht über die erforderlichen Grenzen und die Monate fehlen, wo die Grafen sind 0.
ggplot(data = tmp,
aes(x = as.factor(format(mon, format = "%y/%m")))) +
geom_bar(aes(fill = status)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
Blick auf die Klasse von 'tmp $ mon'. – aosmith