{"id":2794,"date":"2024-10-07T20:17:46","date_gmt":"2024-10-07T11:17:46","guid":{"rendered":"https:\/\/secondlife.lol\/?p=2794"},"modified":"2024-10-07T18:33:39","modified_gmt":"2024-10-07T09:33:39","slug":"confusion-matrix-visualization-with-ggplot2","status":"publish","type":"post","link":"https:\/\/secondlife.lol\/en\/confusion-matrix-visualization-with-ggplot2\/","title":{"rendered":"How to Visualize Confusion Matrices with ggplot2"},"content":{"rendered":"<p class=\"wp-block-paragraph\">In Data Analytics <strong><a href=\"https:\/\/ailib.secondlife.lol\/understanding-confusion-matrix\/\">Confusion Matrix<\/a><\/strong>is an important tool when evaluating the performance of a classification model. In this post, we'll use R's <a href=\"https:\/\/cran.r-project.org\/package=ggplot2\" target=\"_blank\" rel=\"noopener\"><strong>ggplot2<\/strong> Packages<\/a>to visualize confusion matrices, as shown in the figure below, and how to visually represent each element of a confusion matrix to make it easier to understand.<\/p>\n\n\n<style>.kb-image2794_66ca1a-3d .kb-image-has-overlay:after{opacity:0.3;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-right-radius:5px;border-bottom-left-radius:5px;}.kb-image2794_66ca1a-3d img.kb-img, .kb-image2794_66ca1a-3d .kb-img img{border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-right-radius:5px;border-bottom-left-radius:5px;box-shadow:0px 0px 14px 0px rgba(0, 0, 0, 0.2);}<\/style>\n<div class=\"wp-block-kadence-image kb-image2794_66ca1a-3d\"><figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"1200\" height=\"649\" src=\"https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-17.jpg\" alt=\"\ud63c\ub3d9\ud589\ub82c \uc2dc\uac01\ud654 \uadf8\ub9bc\" class=\"kb-img wp-image-2795\" srcset=\"https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-17.jpg 1200w, https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-17-300x162.jpg 300w, https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-17-600x325.jpg 600w, https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-17-768x415.jpg 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><figcaption>(Visualize confusion matrices with ggplot2)<\/figcaption><\/figure><\/div>\n\n\n<style>.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-content-wrap{padding-top:var(--global-kb-spacing-sm, 1.5rem);padding-right:var(--global-kb-spacing-sm, 1.5rem);padding-bottom:var(--global-kb-spacing-sm, 1.5rem);padding-left:var(--global-kb-spacing-sm, 1.5rem);border-top:3px solid var(--global-palette2, #2B6CB0);border-right:3px solid var(--global-palette2, #2B6CB0);border-bottom:3px solid var(--global-palette2, #2B6CB0);border-left:3px solid var(--global-palette2, #2B6CB0);border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-right-radius:5px;border-bottom-left-radius:5px;box-shadow:0px 0px 14px 0px rgba(0, 0, 0, 0.2);}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-contents-title-wrap{padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-contents-title-wrap{color:var(--global-palette2, #2B6CB0);}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-contents-title{color:var(--global-palette2, #2B6CB0);font-size:28px;font-weight:regular;font-style:normal;}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-content-wrap .kb-table-of-content-list{color:var(--global-palette1, #3182CE);line-height:2em;font-weight:regular;font-style:normal;margin-top:var(--global-kb-spacing-sm, 1.5rem);margin-right:0px;margin-bottom:0px;margin-left:0px;}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-content-wrap .kb-table-of-content-list .kb-table-of-contents__entry:hover{color:var(--global-palette6, #718096);}@media all and (max-width: 1024px){.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-content-wrap{border-top:3px solid var(--global-palette2, #2B6CB0);border-right:3px solid var(--global-palette2, #2B6CB0);border-bottom:3px solid var(--global-palette2, #2B6CB0);border-left:3px solid var(--global-palette2, #2B6CB0);}}@media all and (max-width: 1024px){.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-contents-title{font-size:28px;}}@media all and (max-width: 767px){.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-content-wrap{border-top:3px solid var(--global-palette2, #2B6CB0);border-right:3px solid var(--global-palette2, #2B6CB0);border-bottom:3px solid var(--global-palette2, #2B6CB0);border-left:3px solid var(--global-palette2, #2B6CB0);}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-contents-title{font-size:28px;}}<\/style>\n\n\n<h2 class=\"wp-block-heading\">Visualize Confusion Matrices with ggplot2<\/h2>\n\n\n<style>.kb-image2794_52a69e-df .kb-image-has-overlay:after{opacity:0.3;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-right-radius:5px;border-bottom-left-radius:5px;}.kb-image2794_52a69e-df img.kb-img, .kb-image2794_52a69e-df .kb-img img{border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-right-radius:5px;border-bottom-left-radius:5px;box-shadow:0px 0px 14px 0px rgba(0, 0, 0, 0.2);}<\/style>\n<div class=\"wp-block-kadence-image kb-image2794_52a69e-df\"><figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"1200\" height=\"474\" src=\"https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-1-8.jpg\" alt=\"\ud63c\ub3d9\ud589\ub82c \uc2dc\uac01\ud654 \uac1c\uc694 \uadf8\ub9bc\" class=\"kb-img wp-image-2960\" srcset=\"https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-1-8.jpg 1200w, https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-1-8-300x119.jpg 300w, https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-1-8-600x237.jpg 600w, https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-1-8-768x303.jpg 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><figcaption>(Confusion Matrix Visualization Overview)<\/figcaption><\/figure><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">First, <strong>ggplot2<\/strong>is one of the most popular visualization libraries in R. It provides an intuitive way to represent confusion matrices. The code below creates a confusion matrix as a dataframe and passes it to the <strong>ggplot2<\/strong>to visualize confusion matrices, step by step.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. load prerequisite libraries<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To visualize the confusion matrix, we first need to load the ggplot2 library. ggplot2 is essential for many visualizations in R, and is a powerful tool for creating intuitive and stylish plots.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Load # prerequisite libraries\nlibrary(ggplot2)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2. Generate confusion matrix data<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The data representing the confusion matrix is stored in the <strong>Dataframes<\/strong>to create it. Set the predicted and actual values, and add a label (TP, FP, FN, TN) for each entry in the confusion matrix.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Create a data frame representing the # confusion matrix\nconfusion_data &lt;- data.frame(\n  Predicted = factor(c(&quot;Y&quot;, &quot;Y&quot;, &quot;N&quot;, &quot;N&quot;), levels = c(&quot;N&quot;, &quot;Y&quot;)), # predicted: set N and Y levels (N is below)\n  Actual = factor(c(&quot;Y&quot;, &quot;N&quot;, &quot;Y&quot;, &quot;N&quot;), levels = c(&quot;Y&quot;, &quot;N&quot;)), # Actual: Set Y and N levels (Y is left)\n  Label = c(&quot;True Positive (TP)&quot;, &quot;False Positive (FP)&quot;, &quot;False Negative (FN)&quot;, &quot;True Negative (TN)&quot;)  # Label for each item\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Code Description<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Predicted<\/strong> column is the value predicted by the model. Here, the <code>Y<\/code>and <code>N<\/code>where Y is positive and N is negative.<\/li>\n\n\n\n<li><strong>Actual<\/strong> column is the actual value, and the <code>Y<\/code>and <code>N<\/code>to use the<\/li>\n\n\n\n<li><strong>Label<\/strong>are the labels corresponding to each entry in the confusion matrix, representing TP (true positive), FP (false positive), FN (false negative), and TN (true negative).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">3. Visualize the confusion matrix with ggplot2<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now let's visualize the confusion matrix using ggplot2. <strong>geom_<\/strong>tile<strong>()<\/strong>to represent each item as a tile, and add a text label (TP, FP, FN, TN) to each tile.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Visualize the confusion matrix using ggplot2\nggplot(confusion_data, aes(x = Actual, y = Predicted)) +\n  geom_tile(fill = \"lightblue\", color = \"black\", width = 1, height = 1) + # Create a tile, set color and border\n  geom_text(aes(label = Label), size = 5) + # Add a text label to the tile\n  labs(title = \"Confusion Matrix\", subtitle = \"Actual (Reference)\") + # Add title and subtitle\n  scale_x_discrete(position = \"top\") + # Place x-axis label at top\n  theme_minimal() + # Set a minimal theme\n  theme(\n    plot.title = element_text(hjust = 0.5, size = 16, face = \"bold\", margin = margin(b = 10)), # Set title\n    plot.subtitle = element_text(hjust = 0.5, size = 12, face = \"bold\", margin = margin(b = 20)), # Set subtitle\n    axis.title.x = element_blank(), # Remove x-axis title\n    axis.title.y = element_text(size = 12, face = \"bold\", margin = margin(r = 20)), # Set y-axis title\n    axis.text.x = element_text(size = 12, face = \"bold\", margin = margin(b = 10)), # Set x-axis label\n    axis.text.y = element_text(size = 12, face = \"bold\"), # Set y-axis label\n    panel.grid = element_blank(), # Remove grid\n    axis.ticks = element_blank(), # Remove axis tick marks\n    plot.margin = margin(t = 50, b = 40) # set margin\n  )<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Code Description<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>geom_tile()<\/strong>Draws each entry in the confusion matrix in tile format. We set the color of the tiles to light blue and the border to black.<\/li>\n\n\n\n<li><strong>geom_text()<\/strong>: Display the labels (TP, FP, FN, TN) of the confusion matrix above each tile.<\/li>\n\n\n\n<li><strong>labs()<\/strong>: Set the title and subtitle. In the subheading, add \"Actual (Reference)\" to indicate that the actual value is reference data.<\/li>\n\n\n\n<li><strong>theme_minimal()<\/strong>: Set the background to white, and simplify the graph by removing unnecessary elements.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">4. visualize the results and set the graph style<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The result of visualizing the confusion matrix looks like the one at the beginning of the post. Each entry, shown in tiled format, has a <strong>True Positive<\/strong>, <strong>False Positive<\/strong>, <strong>False Negative<\/strong>, <strong>True Negative<\/strong>has been added to help make it easier to understand what the confusion matrix means.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Final full code<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>Load # prerequisite libraries\nlibrary(ggplot2)\n\nCreate a data frame representing the # confusion matrix\nconfusion_data &lt;- data.frame(\n  Predicted = factor(c(&quot;Y&quot;, &quot;Y&quot;, &quot;N&quot;, &quot;N&quot;), levels = c(&quot;N&quot;, &quot;Y&quot;)), # predicted: set N and Y levels (N is below)\n  Actual = factor(c(&quot;Y&quot;, &quot;N&quot;, &quot;Y&quot;, &quot;N&quot;), levels = c(&quot;Y&quot;, &quot;N&quot;)), # Actual: Set Y and N levels (Y is above)\n  Label = c(&quot;True Positive (TP)&quot;, &quot;False Positive (FP)&quot;, &quot;False Negative (FN)&quot;, &quot;True Negative (TN)&quot;)  # Labels for each item\n)\n\n# Visualize the confusion matrix using ggplot2\nggplot(confusion_data, aes(x = Actual, y = Predicted)) +\n  geom_tile(fill = &quot;lightblue&quot;, color = &quot;black&quot;, width = 1, height = 1) +\n  geom_text(aes(label = Label), size = 5) +\n  labs(title = &quot;Confusion Matrix&quot;, subtitle = &quot;Actual (Reference)&quot;) +\n  scale_x_discrete(position = &quot;top&quot;) +\n  theme_minimal() +\n  theme(\n    plot.title = element_text(hjust = 0.5, size = 16, face = &quot;bold&quot;, margin = margin(b = 10)),\n    plot.subtitle = element_text(hjust = 0.5, size = 12, face = &quot;bold&quot;, margin = margin(b = 20)),\n    axis.title.x = element_blank(),\n    axis.title.y = element_text(size = 12, face = &quot;bold&quot;, margin = margin(r = 20)),\n    axis.text.x = element_text(size = 12, face = &quot;bold&quot;, margin = margin(b = 10)),\n    axis.text.y = element_text(size = 12, face = &quot;bold&quot;),\n    panel.grid = element_blank(),\n    axis.ticks = element_blank(),\n    plot.margin = margin(t = 50, b = 40)\n  )<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Finalize<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this post, we'll utilize R's ggplot2 to plot the <strong>Confusion Matrix<\/strong> You've learned how to visualize it. The confusion matrix is an important tool to evaluate the performance of a classification model, and by visually representing the meaning of each entry (TP, FP, FN, TN), it is easy to understand how accurate the model is. This method makes analyzing confusion matrices more intuitive, and you can apply it to a variety of data!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To understand what confusion matrices mean for practical use, you need to understand the <a href=\"https:\/\/secondlife.lol\/en\/r-%eb%8d%b0%ec%9d%b4%ed%84%b0%eb%b6%84%ec%84%9d-%ec%98%88%ec%a0%9c-%eb%b6%93%ea%bd%83-iris-%eb%8d%b0%ec%9d%b4%ed%84%b0%ec%85%8b%ec%9c%bc%eb%a1%9c-%eb%b0%b0%ec%9a%b0%eb%8a%94-%eb%b6%84%eb%a5%98\/\" data-type=\"post\" data-id=\"2785\">R Data Analysis Example: Learn classification and visualization with the Iris Iris dataset<\/a> Review the post. You'll understand what we mean by checking the performance of your model, including accuracy, recall, and more.<\/p>","protected":false},"excerpt":{"rendered":"<p>In data analytics, confusion matrices are an important part of evaluating the performance of classification models...<\/p>","protected":false},"author":3,"featured_media":2962,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_kad_blocks_custom_css":"","_kad_blocks_head_custom_js":"","_kad_blocks_body_custom_js":"","_kad_blocks_footer_custom_js":"","_kad_post_transparent":"","_kad_post_title":"","_kad_post_layout":"","_kad_post_sidebar_id":"","_kad_post_content_style":"","_kad_post_vertical_padding":"","_kad_post_feature":"","_kad_post_feature_position":"","_kad_post_header":false,"_kad_post_footer":false,"_kad_post_classname":"","footnotes":""},"categories":[6],"tags":[328,176,174,327,164,224,209,326,329],"class_list":["post-2794","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-r-coding","tag-false-positive","tag-ggplot2","tag-r-","tag-true-positive","tag-164","tag-224","tag-209","tag-326","tag-329"],"taxonomy_info":{"category":[{"value":6,"label":"\uc54c(R)"}],"post_tag":[{"value":328,"label":"False Positive"},{"value":176,"label":"ggplot2"},{"value":174,"label":"R \ud504\ub85c\uadf8\ub798\ubc0d"},{"value":327,"label":"True Positive"},{"value":164,"label":"\ub370\uc774\ud130 \uc2dc\uac01\ud654"},{"value":224,"label":"\uba38\uc2e0\ub7ec\ub2dd"},{"value":209,"label":"\ubd84\ub958 \ubaa8\ub378"},{"value":326,"label":"\ud63c\ub3d9 \ud589\ub82c"},{"value":329,"label":"\ud63c\ub3d9 \ud589\ub82c \uc2dc\uac01\ud654"}]},"featured_image_src_large":["https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/\ud63c\ub3d9\ud589\ub82c-\uc2dc\uac01\ud654-\ud3ec\uc2a4\ud2b8-\uc378\ub124\uc77c-1-600x600.jpg",600,600,true],"author_info":{"display_name":"TERE","author_link":"https:\/\/secondlife.lol\/en\/author\/tere\/"},"comment_info":0,"category_info":[{"term_id":6,"name":"\uc54c(R)","slug":"r-coding","term_group":0,"term_taxonomy_id":6,"taxonomy":"category","description":"","parent":20,"count":61,"filter":"raw","cat_ID":6,"category_count":61,"category_description":"","cat_name":"\uc54c(R)","category_nicename":"r-coding","category_parent":20}],"tag_info":[{"term_id":328,"name":"False Positive","slug":"false-positive","term_group":0,"term_taxonomy_id":328,"taxonomy":"post_tag","description":"","parent":0,"count":1,"filter":"raw"},{"term_id":176,"name":"ggplot2","slug":"ggplot2","term_group":0,"term_taxonomy_id":176,"taxonomy":"post_tag","description":"","parent":0,"count":15,"filter":"raw"},{"term_id":174,"name":"R \ud504\ub85c\uadf8\ub798\ubc0d","slug":"r-%ed%94%84%eb%a1%9c%ea%b7%b8%eb%9e%98%eb%b0%8d","term_group":0,"term_taxonomy_id":174,"taxonomy":"post_tag","description":"","parent":0,"count":15,"filter":"raw"},{"term_id":327,"name":"True Positive","slug":"true-positive","term_group":0,"term_taxonomy_id":327,"taxonomy":"post_tag","description":"","parent":0,"count":1,"filter":"raw"},{"term_id":164,"name":"\ub370\uc774\ud130 \uc2dc\uac01\ud654","slug":"%eb%8d%b0%ec%9d%b4%ed%84%b0-%ec%8b%9c%ea%b0%81%ed%99%94","term_group":0,"term_taxonomy_id":164,"taxonomy":"post_tag","description":"","parent":0,"count":52,"filter":"raw"},{"term_id":224,"name":"\uba38\uc2e0\ub7ec\ub2dd","slug":"%eb%a8%b8%ec%8b%a0%eb%9f%ac%eb%8b%9d","term_group":0,"term_taxonomy_id":224,"taxonomy":"post_tag","description":"","parent":0,"count":7,"filter":"raw"},{"term_id":209,"name":"\ubd84\ub958 \ubaa8\ub378","slug":"%eb%b6%84%eb%a5%98-%eb%aa%a8%eb%8d%b8","term_group":0,"term_taxonomy_id":209,"taxonomy":"post_tag","description":"","parent":0,"count":2,"filter":"raw"},{"term_id":326,"name":"\ud63c\ub3d9 \ud589\ub82c","slug":"%ed%98%bc%eb%8f%99-%ed%96%89%eb%a0%ac","term_group":0,"term_taxonomy_id":326,"taxonomy":"post_tag","description":"","parent":0,"count":1,"filter":"raw"},{"term_id":329,"name":"\ud63c\ub3d9 \ud589\ub82c \uc2dc\uac01\ud654","slug":"%ed%98%bc%eb%8f%99-%ed%96%89%eb%a0%ac-%ec%8b%9c%ea%b0%81%ed%99%94","term_group":0,"term_taxonomy_id":329,"taxonomy":"post_tag","description":"","parent":0,"count":1,"filter":"raw"}],"_links":{"self":[{"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/posts\/2794","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/comments?post=2794"}],"version-history":[{"count":9,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/posts\/2794\/revisions"}],"predecessor-version":[{"id":2963,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/posts\/2794\/revisions\/2963"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/media\/2962"}],"wp:attachment":[{"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/media?parent=2794"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/categories?post=2794"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/tags?post=2794"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}