Plotting a data.frame in R

11,509

Solution 1

The doctor prescribes a slight modification to Roman's data frame.

library(ggplot2)
my.cars <- data.frame(
  Toyota = runif(50), 
  Mazda = runif(50), 
  Renault = runif(50),
  Car = paste("Car", 1:50, ".txt", sep = "")  
)

my.cars.melted <- melt(my.cars, id.vars = "Car")

He then suggests that it looks like the car variable is categorical, so your first choice would be a barchart.

p_bar <- ggplot(my.cars.melted, aes(Car, value, fill = variable)) +
  geom_bar(position = "dodge")
p_bar

He then notes that for 95 cars, this could get a bit cumbersome. Perhaps a dotplot would be more suitable.

p_dot <- ggplot(my.cars.melted, aes(Car, value, col = variable)) +
  geom_point() +
  opts(axis.text.x = theme_text(angle = 90))
p_dot

As this is still a little tricky to get useful information out of, it might be best to order the cars by the average value (whatever value means)

my.cars.melted$Car <- with(my.cars.melted, reorder(Car, value))

(Then redraw p_dot as before.)

Finally, the doctor notes that you can draw the line plot that Roman recommended with

p_lines <- ggplot(my.cars.melted, aes(as.numeric(Car), value, col = variable)) +
  geom_line()
p_lines

Solution 2

This should get you started.

my.cars <- data.frame(Toyota = runif(50), Mazda = runif(50), Renault = runif(50)) #make some fake data for this example
plot(x = 1:nrow(my.cars), y = my.cars$Toyota, type = "n") #make an empty plot
with(my.cars, lines(x = 1:nrow(my.cars), y = Toyota, col = "red")) #add lines for Toyota
with(my.cars, lines(x = 1:nrow(my.cars), y = Mazda, col = "red")) # add lines for Mazda
with(my.cars, lines(x = 1:nrow(my.cars), y = Renault, col = "navy blue")) # add lines for Renault

I used with() so that you don't have to type my.cars$Toyota, my.cars$Mazda... every time you want to call a column. Explore ?par for further parameters that can be passed to plot. A doctor with a ggplot2 solution will see you shortly.

Share:
11,509
digitalaxp
Author by

digitalaxp

Updated on June 27, 2022

Comments

  • digitalaxp
    digitalaxp almost 2 years

    i'm new to R and i need advise in plotting a dataframe in R which looks like this:

             V1          V2         V3          V4         
              1       Mazda     Toyota     Peugeot
       Car1.txt 0,507778837 0,19834711 0,146892655
       Car2.txt 0,908717802 0,64214047 0,396508728
    

    i would like to plot this dataframe ( which in fact has 7 columns and 95 rows) in a single graph, where v2, v3, v4 represent a line in a different color and named like the car names , V1 as label of the x-axis, whereas the y-axis is in the range[0,1].

    I have really no clue how to do this, so i'm very thankful for any advice