title: “R语言Plotly绘图包package简单应用”
author:
- czliutz
documentclass: ctexart
keywords: - 中文
- R Markdown
output:
rticles::ctex:
fig_caption: yes
number_sections: yes
toc: yes
使用plotly绘制直条图bar Chart
library(plotly)
fig <- plot_ly(x = c(0,1, 2), y = c(2, 1, 3), type = 'bar') %>%
layout(title = 'A Figure Displayed with print(fig)',
plot_bgcolor='#e5ecf6',
xaxis = list(
zerolinecolor = '#ffff',
zerolinewidth = 1,
gridcolor = 'ffff'),
yaxis = list(
zerolinecolor = '#ffff',
zerolinewidth = 1,
gridcolor = 'ffff'))
print(fig)
1.plot和ggplot混合使用
library(plotly)
library(ggplot2)
p <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(aes(color=Species, shape=Species)) +
labs(title = "Iris sepal width vs length")
ggplotly(p)
2.plot和ggplot混合使用
library(plotly)
library(ggplot2)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
head(d)
p <- ggplot(data = d, aes(x = carat, y = price)) +
geom_point(aes(text = paste("Clarity:", clarity)), size = 4) +
geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~ cut)
ggplotly(p)
3.ployly绘图中add类函数应用
library(plotly)
head(economics)
p <- plot_ly(economics, x = ~date, y = ~uempmed)
p
# scatter trace with mode of text
add_text(p, text = "%")
# scatter trace with mode of lines
add_paths(p)
# like `add_paths()`, but ensures points are connected according to `x`
add_lines(p)
4.绘制动态图
library(plotly)
plot_ly(mtcars, x = ~wt, y = ~mpg, frame = ~cyl) %>%
animation_opts(transition = 0)
题外话Discriptive Statistics
描述性统计summary()
myvars<-c("mpg",'hp','wt')
summary(mtcars[myvars])
sapply()
mystats <- function(x, na.omit=FALSE){
if (na.omit)
x <- x[!is.na(x)]
m <- mean(x)
n <- length(x)
s <- sd(x)
skew <- sum((x-m)^3/s^3)/n
kurt <- sum((x-m)^4/s^4)/n - 3
return(c(n=n, mean=m, stdev=s,
skew=skew, kurtosis=kurt))
}
myvars <- c("mpg", "hp", "wt")
sapply(mtcars[myvars], mystats)