问题
I have the following data frame:
vector_builtin vector_loop vector_recursive
1 0.00 0.10 0.34
2 0.00 0.10 0.36
3 0.00 0.08 0.36
4 0.00 0.11 0.34
5 0.00 0.11 0.36
I want to display the three columns in a line chart.
I have imported ggplot2 into R and the chart is displaying without data or lines in it.
Code:
library(ggplot2)
indexes <- row.names(df.new)
ggplot(df.new, aes(x=vector_recursive, y=indexes))
Chart output
Output I want A chart showing the three series in a line chart.
回答1:
A very basic example using ggplot2
and df from OP can be:
df <- read.table(text = "time vector_builtin vector_loop vector_recursive
1 0.00 0.10 0.34
2 0.00 0.10 0.36
3 0.00 0.08 0.36
4 0.00 0.11 0.34
5 0.00 0.11 0.36", header = T, stringsAsFactors = F)
p <- ggplot() +
geom_line(aes(time, vector_builtin, colour = "red"), data = df) +
geom_line(aes(time, vector_loop, colour = "green"), data = df) +
geom_line(aes(time, vector_recursive, colour = "blue"), data = df) +
labs(x="Time(s)", y="Value") + # Labels for axis
scale_color_manual("Data Types", values=c(red="red",green="green",blue="blue"),
labels=c("vector_builtin", "vector_loop", "vector_recursive" ))
print(p)
回答2:
Make sure that you have your data in a format that ggplot2
understands. In your code, geom_line
is expecting you to provide which columns in your data should correspond to which question. Below I have recreated your data, in the future, consider using dput
to provide the data to others, which will help troubleshoot your specific issue.
df=data.frame(vector_builtin=c(0.00,0.00,0.00,0.00,0.00),
vector_loop=c(0.10,0.10,0.08,0.11,0.11),
vector_recursive=c(0.34,0.36,0.36,0.34,0.36))
However, you don't specify what your x axis is, so we will create a new variable that holds that information, for example:
df$x=1:5
Now, I would recommend reshaping the data into long format, which is preferred by ggplot2
. You could also use the other answer here and specify each without that problem, but reshape2
's melt
function could be used.
library(reshape2)
df.m = melt(df, id.vars="x")
Now when you correctly identify the names of the columns to plot, ggplot2
will plot the data correctly:
ggplot() + geom_line(aes(color=variable, x=x, y=value), data=df.m)
来源:https://stackoverflow.com/questions/48491246/chart-in-r-not-displaying-data