{"id":2965,"date":"2023-01-19T08:48:11","date_gmt":"2023-01-19T00:48:11","guid":{"rendered":"http:\/\/cnliutz.uicp.io\/?p=2965"},"modified":"2023-01-19T08:48:11","modified_gmt":"2023-01-19T00:48:11","slug":"r%e5%9f%ba%e6%9c%ac%e7%bb%98%e5%9b%be%e6%96%b9%e6%b3%95","status":"publish","type":"post","link":"http:\/\/g1n29wqq.ipyingshe.net:5347\/?p=2965","title":{"rendered":"R\u57fa\u672c\u7ed8\u56fe\u65b9\u6cd5"},"content":{"rendered":"\n<pre class=\"wp-block-code\"><code>---\ntitle: \"R Basic Chart\"\nauthor:\n  - \u5218\u94c1\u67f1\ndocumentclass: ctexart\nkeywords:\n  - \u4e2d\u6587\n  - R Markdown\noutput:\n  rticles::ctex:\n    fig_caption: yes\n    number_sections: yes\n    toc: yes\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n# R Basic Graphs\n\nFrom R in Action Third  edition Chapter 6\n\n```{r pressure, echo=FALSE}\nplot(pressure)\n```\n\nNote that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.\n\n## Bar Chart\n\n```{r}\ndata(Arthritis,package = \"vcd\")\ntable(Arthritis$Improved)\n\nlibrary(ggplot2)\n\n#Simple bar chart\nggplot(Arthritis, aes(x=Improved)) + geom_bar() + \n labs(title=\"Simple Bar chart\", \n x=\"Improvement\", \n y=\"Frequency\")      \n\n#Horizontal bar chart\nggplot(Arthritis, aes(x=Improved)) + geom_bar() + \n labs(title=\"Horizontal Bar chart\", \n x=\"Improvement\", \n y=\"Frequency\") + \n coord_flip()    \n\n```\n\n#### Stacked, grouped, and filled bar charts\n\n```{r}\nlibrary(ggplot2)\ntable(Arthritis$Improved, Arthritis$Treatment)\n#\u2776Stacked bar chart\nggplot(Arthritis, aes(x=Treatment, fill=Improved)) + \n geom_bar(position = \"stack\") + \n labs(title=\"Stacked Bar chart\", \n x=\"Treatment\", \n y=\"Frequency\") \n#\u2777 Grouped bar chart\nggplot(Arthritis, aes(x=Treatment, fill=Improved)) + \n geom_bar(position = \"dodge\") + \n labs(title=\"Grouped Bar chart\", \n x=\"Treatment\", \n y=\"Frequency\") \n#\u2778 Filled bar chart\nggplot(Arthritis, aes(x=Treatment, fill=Improved)) + \n geom_bar(position = \"fill\") + \n labs(title=\"Filled Bar chart\", \n x=\"Treatment\", \n y=\"Proportion\")\n```\n\n```{r cars}\nsummary(cars)\n```\n\n\n#### Bar chart for sorted mean values\n\u2776 Generates means by region\n\u2777 Plots means in a sorted bar chart\n\n```{r}\n\nstates &lt;-data.frame(state.region,state.x77)\nlibrary(dplyr)\nlibrary(ggplot2)\nplotdata &lt;-states %>%\n  group_by(state.region) %>%\n  summarize(mean=mean(Illiteracy))   #Illiteracy\u6587\u76f2\nplotdata\nggplot(plotdata, aes(x=reorder(state.region, mean), y=mean)) + \n geom_bar(stat=\"identity\") + \n labs(x=\"Region\", \n y=\"\", \n title = \"Mean Illiteracy Rate\")\n\n```\n\n#### Bar chart label\n\n```{r}\nggplot(mpg, aes(x=model)) + \n geom_bar() +\n labs(title=\"Car models in the mpg dataset\", \n y=\"Frequency\", x=\"\")\n\nggplot(mpg, aes(x=model)) + \n geom_bar() +\n labs(title=\"Car models in the mpg dataset\", \n y=\"Frequency\", x=\"\") +\n coord_flip()\n\nggplot(mpg, aes(x=model)) + \n geom_bar() +\n labs(title=\"Model names in the mpg dataset\", \n y=\"Frequency\", x=\"\") +\n theme(axis.text.x = element_text(angle = 45, hjust = 1, size=8))\n\n\n```\n\n## Pie Chart\n\nggpie(data, x, by, offset, percent, legend, title)\nwhere\n- data is a data frame.\n\n- x is the categorical variable to be plotted.\n\n- by is an optional second categorical variable. If present, a\npie will be produced for each level of this variable.\n\n- offset is the distance of the pie slice labels from the\norigin. A value of 0.5 will place the labels in the center of\nthe slices, and a value greater than 1.0 will place them\noutside the slice.\n\n- percent is logical. If FALSE, percentage printing is\nsuppressed.\n\n- legend is logical. If FALSE, the legend is omitted, and each\npie slice is labeled.\n\n- title is an option title.\n```{r}\n\nif(!require(remotes)) install.packages(\"remotes\")\n{remotes::install_github(\"rkabacoff\/ggpie\") }\n\nlibrary(ggplot2)\nlibrary(ggpie)\nggpie(mpg, class)\nggpie(mpg, class, legend=FALSE, offset=1.3, \n title=\"Automobiles by Car Class\")\nggpie(mpg, class, year, \n legend=FALSE, offset=1.3, title=\"Car Class by Year\")\n\n\npie(table(mpg$class))\n```\n\n## Tree maps\n\n```{r}\nlibrary(ggplot2)\nlibrary(dplyr)\nlibrary(treemapify)\n#\u2776 Summarizes the data\nplotdata &lt;- mpg %>% count(manufacturer)\n#\u2777 Creates the tree map\nggplot(plotdata, \n aes(fill = manufacturer, \n area = n, \n label = manufacturer)) + \ngeom_treemap() + \ngeom_treemap_text() + \ntheme(legend.position = \"none\") \n\n```\n\n###Tree map with subgrouping\n\n```{r}\nlibrary(ggplot2)\nlibrary(dplyr)\nlibrary(treemapify)\nplotdata &lt;- mpg %>% \n count(manufacturer, drv)  # Computes cell counts\n plotdata$drv &lt;- factor(plotdata$drv, \n levels=c(\"4\", \"f\", \"r\"), \n labels=c(\"4-wheel\", \"front-wheel\", \"rear\"))   # Provides better labels for drivetrains\n#\u2778 Creates tree map\nggplot(plotdata, \n aes(fill = manufacturer, \n area = n, \n label = manufacturer, \n subgroup=drv)) + \n geom_treemap() + \n geom_treemap_subgroup_border() + \n geom_treemap_subgroup_text( \n place = \"middle\", \n colour = \"black\", \n alpha = 0.5, \n grow = FALSE) + \n geom_treemap_text(colour = \"white\", \n place = \"centre\", \n grow=FALSE) + \n theme(legend.position = \"none\")\n```\n\n\n## hist\n\n```{r}\nlibrary(lattice)\nhead(singer)\nhistogram(~height | voice.part, data = singer,\nmain=\"Distribution of Heights by Voice Pitch\",\nxlab=\"Height (inches)\")\n```\n\n```{r}\nsummary(women)\nfit &lt;- lm(weight ~ height, data=women)\nsummary(fit)\nplot(women)\n```\n\n```{r}\nhist(mtcars$mpg, \n     freq=FALSE, \n     breaks=12, \n     col=\"red\", \n     xlab=\"Miles Per Gallon\", \n     main=\"Histogram, rug plot, density curve\")  \nrug(jitter(mtcars$mpg))   #\u5730\u6bef\u3001\u6296\u52a8\nlines(density(mtcars$mpg), col=\"blue\", lwd=2)\n```\n\n### Histograms\n\nHistograms display the distribution of a continuous variable by\ndividing the range of scores into a specified number of bins on\n267\nthe x-axis and displaying the frequency of scores in each bin on\nthe y-axis. You can create histograms using:\n\nggplot(data, aes(x = contvar)) + geom_histogram()\n```{r}\nlibrary(ggplot2)\nlibrary(scales)\ndata(mpg)\n#Simple histogram\n\ncars2008 &lt;- mpg&#91;mpg$year == 2008, ]\nggplot(cars2008, aes(x=cty)) + \n geom_histogram() + \n labs(title=\"Default histogram\") \n\n# Colored histogram with 20 bins\nggplot(cars2008, aes(x=hwy)) + \n geom_histogram(bins=20, color=\"white\", fill=\"steelblue\") + \n labs(title=\"Colored histogram with 20 bins\", \n x=\"City Miles Per Gallon\", \n y=\"Frequency\")\n\n#Histogram with percentages\nggplot(cars2008, aes(x=hwy, y=after_stat(density))) + \n geom_histogram(bins=20, color=\"white\", fill=\"steelblue\") + \n scale_y_continuous(labels=scales::percent) + \n labs(title=\"Histogram with percentages\", \n y= \"Percent\",\n x=\"City Miles Per Gallon\")\n\n# Histogram with density curve\nggplot(cars2008, aes(x=cty, y=after_stat(density))) + \n geom_histogram(bins=20, color=\"white\", fill=\"steelblue\") + \n scale_y_continuous(labels=scales::percent) + \n geom_density(color=\"red\", size=1) + \n labs(title=\"Histogram with density curve\", \n y=\"Percent\" , \n x=\"Highway Miles Per Gallon\")\n```\n\n-\u300aR In Action\u300b third edtion, page 267\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[15],"tags":[],"class_list":["post-2965","post","type-post","status-publish","format-standard","hentry","category-r"],"_links":{"self":[{"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/2965","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2965"}],"version-history":[{"count":1,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/2965\/revisions"}],"predecessor-version":[{"id":2966,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/2965\/revisions\/2966"}],"wp:attachment":[{"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2965"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2965"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2965"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}