Reputation: 15010
I have a data frame like this
>df
X1 X2 X3 X4 X5 X6
2016-02-16 120.1142 124.8521 119.0029 119.2219 129.4915 116.5805
2016-02-17 122.1224 121.7848 123.8320 125.2890 125.6411 119.2096
2016-02-18 123.7764 126.1593 126.2566 120.5896 124.5153 123.2499
2016-02-19 119.5436 124.8069 118.0718 121.8618 123.3318 123.5650
2016-02-20 123.5873 126.0524 121.6285 118.9005 122.1214 123.5694
I want to plot histogram with column name as the title.
I am using this code
par(mfrow = c(2,3))
for(i in names(df)){
hist(df[[i]], main=colnames(df[[i]]),xlab="x")
}
buts its showing nothing.
> colnames(df[[i]])
NULL
How can i plot histogram with column name?
Upvotes: 0
Views: 2138
Reputation: 94202
What you've done here doesn't work:
par(mfrow = c(2,3))
for(i in names(df)){
hist(df[[i]], main=colnames(df[[i]]),xlab="x")
}
because df[[i]]
is just the vector from the data frame, and vectors don't have colnames. You've already got the name you want in i
, so why not:
hist(df[[i]], main=i, xlab="x")
It might be better practice not to call your loop variable i
, because that smells like a number to most people. Use n
or name
for clarity.
Upvotes: 2
Reputation: 388982
Try mapply
mapply(hist,as.data.frame(df),main=colnames(df),xlab="x")
Upvotes: 5