{"id":6744,"date":"2020-11-11T16:21:49","date_gmt":"2020-11-11T10:51:49","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=6744"},"modified":"2020-11-11T16:21:51","modified_gmt":"2020-11-11T10:51:51","slug":"controlling-figure-aesthetics-using-seaborn","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/controlling-figure-aesthetics-using-seaborn\/","title":{"rendered":"Controlling figure aesthetics using seaborn"},"content":{"rendered":"\n<p>Drawing attractive figures are important. When making figures for yourself, as you explore a dataset, it\u2019s nice to have plots that are pleasant to look at. Visualizations are also central to communicating quantitative insights to an audience, and in that setting, it\u2019s even more necessary to have figures that catch the attention and draw a viewer in.&nbsp;<\/p>\n\n\n\n<p><a href=\"https:\/\/www.h2kinfosys.com\/blog\/introduction-to-data-visualization-using-matplot\/\">Matplotlib <\/a>is highly customizable, but it can be hard to know what settings to tweak to achieve an attractive plot. Seaborn comes with several customized themes and a high-level interface for controlling the look of matplotlib figures.\u00a0<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import numpy as np&nbsp;&nbsp;\nimport seaborn as sns&nbsp;&nbsp;\nimport matplotlib.pyplot as plot&nbsp;&nbsp;<\/pre>\n\n\n\n<p>Let\u2019s define a simple function to plot some offset sine waves, which will help us see the different stylistic parameters we can tweak.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>def <\/strong>sinplot(flip=1):&nbsp;&nbsp;\n&nbsp;x = np.linspace(0, 14, 100)&nbsp;&nbsp;\n&nbsp;<strong>for <\/strong>i <strong>in <\/strong>range(1, 7):&nbsp;&nbsp;\n&nbsp;plt.plot(x, np.sin(x + i * .5)*(7 - i)*flip)&nbsp;&nbsp;<\/pre>\n\n\n\n<p>This is what the plot looks like with matplotlib defaults&nbsp;<\/p>\n\n\n\n<p>sinplot()<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh3.googleusercontent.com\/m_5mpc4u3DLPvVgWVKO0mRq_5S5mPUMkQpeDCgerCIjELKmSJ6ftmk6nn-dvzUS8B-wEF2LQXtWzr3N5l1OTht7Dw6edlEQEdlmYxVqYTuZALxC-HWYxJ8ksMHdZN8qE6gMqIqX_\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<p>To switch to seaborn defaults, simply call the <strong>set_theme() <\/strong>function. sns.set_theme()&nbsp;&nbsp;<\/p>\n\n\n\n<p>sinplot()&nbsp;&nbsp;<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh3.googleusercontent.com\/43prLBJXytYm-kUPlnUasncrK0PFnCP9OKRFZOz4wsr2uA8Ahiv7LPnk6q7Zfg1370Hjtp1PA9qLwVA8mH8YGQpchHyD0qBjWrD0SkNozoIshX67YFbJvhJWxfaM1yciKjGyuc3q\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<p>Note that in versions of seaborn before 0.8, set_theme() was called on import. In later versions, it must be explicitly invoked.&nbsp;<\/p>\n\n\n\n<p><a href=\"https:\/\/seaborn.pydata.org\/introduction.html\" rel=\"nofollow noopener\" target=\"_blank\">Seaborn <\/a>splits matplotlib parameters into two independent groups. The first group sets the aesthetic style of the plot, and the second scale various elements of the figure so that it can be easily incorporated into different contexts.\u00a0<\/p>\n\n\n\n<p>The interface for manipulating these parameters are two pairs of functions. To control the style, use the axes_style() and set_style() functions.&nbsp;&nbsp;<\/p>\n\n\n\n<p>To scale the plot, use the plotting_context() and set_context() functions. In both cases, the first function returns a dictionary of parameters, and the second sets the matplotlib defaults.<\/p>\n\n\n\n<p>Seaborn figure styles&nbsp;&nbsp;<\/p>\n\n\n\n<p>There are five preset seaborn themes: darkgrid, whitegrid, dark, white,\u00a0 and ticks. They are each suited to different applications and personal preferences. The default theme is darkgrid. As mentioned above, the grid helps the plot serve as a lookup table for quantitative information,\u00a0 and the white-on grey helps to keep the grid from competing with lines that represent data. The whitegrid theme is similar, but it is better suited\u00a0 to plots with heavy data elements\u00a0<\/p>\n\n\n\n<p>sns.set_style(&#8220;whitegrid&#8221;)&nbsp;&nbsp;<\/p>\n\n\n\n<p>data = np.random.normal(size=(20, 6)) + &nbsp;<\/p>\n\n\n\n<p>np.arange(6) \/ 2&nbsp;&nbsp;<\/p>\n\n\n\n<p>sns.boxplot(data=data);&nbsp;<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh5.googleusercontent.com\/4auTrOJ25ARz16HoOF9Its4iymFK4KLmgovUlh-7I1tfy6Z13VTIgEUJMeZc56NVxxSu1gQcooUeUoS2WWO5G-5fAxQMG39IWT7EnzOSFGJRIZSU1nXFMS45T_AZERifjNMIjo5p\" alt=\"matplotlib figures\" title=\"\"><\/figure>\n\n\n\n<p>For many plots, especially for settings like talks, where you primarily want to use figures to provide impressions of patterns in the data, the grid is less necessary.&nbsp;<\/p>\n\n\n\n<p>sns.set_style(\u201cdark&#8221;)&nbsp;&nbsp;<\/p>\n\n\n\n<p>sinplot()&nbsp;<\/p>\n\n\n\n<p><img fetchpriority=\"high\" decoding=\"async\" src=\"https:\/\/lh5.googleusercontent.com\/4dk5UZOKAiui5PS1ILla8klVeEu9fGaspcy14CqyXGaS3rAi3y_bSJ14EX1O8HEnY-9ISSIxVZQQ5V2vIUt0Cdtuu7ONPxvdM5QohL-XdO04Xg6BVZl3kkakk6I8b2Ka5rpsNlJT\" width=\"495\" height=\"335\" alt=\"\" title=\"\"><strong>Removing axes spines&nbsp;&nbsp;<\/strong><\/p>\n\n\n\n<p>Both the white and ticks styles can benefit from removing the top and right axes spines, which are not needed. The seaborn function&nbsp; despine() can be called to remove them&nbsp;<\/p>\n\n\n\n<p>sinplot()&nbsp;&nbsp;<\/p>\n\n\n\n<p>sns.despine()<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh3.googleusercontent.com\/PxmZDcRHZ7Ejlt4XpXwPttealBVdrj--Bngp5SSZE6VKTG4ljER8a-F0YKgh5todxi0IqBgMYKUg3mzALQmVG4FKxalsTJrAFoGJ-g-FqUzxTrdBiLGGzdympQ6cnEzWRjKFuCjt\" alt=\"matplotlib figures\" title=\"\"><\/figure>\n\n\n\n<p>Some plots benefit from offsetting the spines away from the data, which&nbsp; can also be done when calling <strong>despine()<\/strong>.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">f, ax = plt.subplots()&nbsp;&nbsp;\nsns.violinplot(data=data)&nbsp;&nbsp;\nsns.despine(offset=10, trim=<strong>True<\/strong>);&nbsp;<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh6.googleusercontent.com\/g7hYLAMAFVovuZyTh6tRkCTY6LJZhvrMRewoon9uxb950BRKRJ7WTGDOt7-8OvG7Qfb9PgWrvFETkeAtnXfqib3DkvFicDF08cYro8BlnSQ4u-3Bdr7Z7io3aPoHCtREWjSLaXwV\" alt=\"matplotlib figures\" title=\"\"><\/figure>\n\n\n\n<p>You can also control which spines are removed with additional&nbsp; arguments to <strong>despine()&nbsp;<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">sns.set_style(\"whitegrid\")&nbsp;&nbsp;\nsns.boxplot(data=data, palette=\"deep\")&nbsp;&nbsp;\nsns.despine(left=<strong>True<\/strong>)<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh6.googleusercontent.com\/SzvP41jw5J2YK8M-r-VUv4rbOTg1-ShsNNJpt0rifBRbvsqx_sQ4t9lqohq2ux25sad2LueryQ81AiWGSgXOLDky7sB_mIvXWohQlwqwSR_JUB8DSlHAmEIYgq7b9yiUDYT_ayF7\" alt=\"matplotlib figures\" title=\"\"><\/figure>\n\n\n\n<p><strong>Temporarily setting figure style&nbsp;&nbsp;<\/strong><\/p>\n\n\n\n<p>Although it\u2019s easy to switch back and forth, you can also use the\u00a0 axes_style() function in a with statement to temporarily set plot\u00a0 parameters. This also allows you to make matplotlib figures with differently-styled\u00a0 axes\u00a0<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">f = plt.figure(figsize=(6, 6))&nbsp;&nbsp;\ngs = f.add_gridspec(2, 2)&nbsp;&nbsp;\n<strong>with <\/strong>sns.axes_style(\"darkgrid\"):&nbsp;&nbsp;\n&nbsp;ax = f.add_subplot(gs[0, 0])&nbsp;&nbsp;\n&nbsp;sinplot()&nbsp;&nbsp;\n<strong>with <\/strong>sns.axes_style(\"white\"):&nbsp;&nbsp;\n&nbsp;ax = f.add_subplot(gs[0, 1])&nbsp;&nbsp;\n&nbsp;sinplot()&nbsp;&nbsp;\n<strong>with <\/strong>sns.axes_style(\"ticks\"):&nbsp;&nbsp;\n&nbsp;ax = f.add_subplot(gs[1, 0])&nbsp;&nbsp;\n&nbsp;sinplot()&nbsp;&nbsp;\n<strong>with <\/strong>sns.axes_style(\"whitegrid\"):&nbsp;&nbsp;\n&nbsp;ax = f.add_subplot(gs[1, 1])&nbsp;&nbsp;\n&nbsp;sinplot()&nbsp;&nbsp;\nf.tight_layout()<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh6.googleusercontent.com\/Lz_rgSGF6Jkmr6hjbi3WXhrKy0ob4VpHIVfgePpSUpmOiwlZhNFO-ZySDWyg_FYS9pdYUwBsTLnApu-xo-IdodROTQPgz44e0mVUBS3GyZ4zUAz60yJxXvVuZa4ra3zYEltgymNx\" alt=\"matplotlib figures\" title=\"\"><\/figure>\n\n\n\n<p><strong>Overriding elements of the seaborn styles&nbsp;&nbsp;<\/strong><\/p>\n\n\n\n<p>If you want to customize the seaborn styles, you can pass a dictionary of parameters to the rc argument of axes_style() and set_style(). Note that you can only override the parameters that are part of the style definition through this method. However, the higher level set_theme() function takes a dictionary of any matplotlib parameters.&nbsp;<\/p>\n\n\n\n<p>If you want to see what parameters are included, you can just call the&nbsp; function with no arguments, which will return the current settings:&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">sns.axes_style()&nbsp;&nbsp;<\/pre>\n\n\n\n<p>You can then set different versions of these parameters: sns.set_style(&#8220;darkgrid&#8221;, {&#8220;axes.facecolor&#8221;: \u201c.9&#8243;})&nbsp; sinplot()&nbsp;<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh4.googleusercontent.com\/xubRmJvahZ-aEBNcYqEfNfeODLOrDVzfwOaB85PeLsAY0N7xX79jZFdMKOuPfwiDB0Bv2-y3sJzdYNiMbOpTDcjVh4VIXHJNFJ8Se-n0pTySntSL73jHq_2tfQmnzo_U4ng4leun\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<p><strong>Scaling plot elements&nbsp;&nbsp;<\/strong><\/p>\n\n\n\n<p>A separate set of parameters control the scale of plot elements, which should let you use the same code to make plots that are suited for use in settings where larger or smaller plots are appropriate.&nbsp;<\/p>\n\n\n\n<p>First let\u2019s reset the default parameters by calling set_theme()&nbsp; sns.set_theme()&nbsp;&nbsp;<\/p>\n\n\n\n<p>The four preset contexts, in order of relative size, are paper, notebook,&nbsp; talk, and poster. The notebook style is the default and was used in the&nbsp; plots above.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">sns.set_context(\u201cpaper\")&nbsp;&nbsp;<\/pre>\n\n\n\n<p>sinplot()&nbsp;<\/p>\n\n\n\n<p><img decoding=\"async\" src=\"https:\/\/lh6.googleusercontent.com\/5rHaxyaabzsViD80qArrZuSbbGoBgrX7_QOho42y8H2qF-ENe-czPK2lWIsVggYr32nvvJD2l5FBMY6K4jITKhPAMJ-YlmZNS9mtKqM3Jz2wpp006HJhW_6iTy7sg5Eg1RTlh73G\" width=\"489\" height=\"332\" alt=\"\" title=\"\">sns.set_context(\u201ctalk&#8221;)&nbsp;&nbsp;<\/p>\n\n\n\n<p>sinplot()&nbsp;<\/p>\n\n\n\n<p><img decoding=\"async\" src=\"https:\/\/lh3.googleusercontent.com\/o574mdHzMD9xKVRwrXbc3_6gQ5bUx1uiTmU__GOftBro138R4uo87uohPnoSlDJvcVNgFFzUd0A_bWrifpYxRBNsNqPXXueqSmW3-SZWM2mo6wSurFaMHMPlhYYAyt7l23IdgF3p\" width=\"525\" height=\"345\" alt=\"\" title=\"\">sns.set_context(\u201cposter&#8221;)&nbsp;&nbsp;<\/p>\n\n\n\n<p>sinplot()&nbsp;&nbsp;<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh3.googleusercontent.com\/Mu2DFn-yz15tPguVPi_RR8cyTx6i1HhTzY-0AHyMa4dSaLdgX1E_nlvWdgah-jET2-r7rWW0cQT8j52wCarMw_e7TZXI2F5h99RSq2pf05fgmjlpBhk3vi3G0LOnQyrZSC0xm9Fq\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<p>Most of what you now know about the style functions should transfer to&nbsp; the context functions.<\/p>\n\n\n\n<p>You can call <strong>set_context() <\/strong>with one of these names to set the parameters, and you can override the parameters by providing a&nbsp; dictionary of parameter values.&nbsp;<\/p>\n\n\n\n<p>You can also independently scale the size of the font elements when changing the context. This option is also available through the top-level <strong>set() <\/strong>function.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">sns.set_context(\"notebook\", font_scale=1.5,&nbsp; rc={\"lines.linewidth\": 2.5})&nbsp;&nbsp;<\/pre>\n\n\n\n<p>sinplot()&nbsp;<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh3.googleusercontent.com\/0nrkDrTwRp0L8dEDQgfggkVh_5OVYXlsZCVoouXGJ8G8ooC-tGrYcAiWGsUrl2TDjIzYaZXv1Mu10d5OvZ3Mt1VREvN16X4RgH6cRILURmRs1dICKDikEY6SGb7GDTTNBhzppuqu\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<p>Similarly, you can temporarily control the scale of matplotlib figures nested under a with the statement.\u00a0Both the style and the context can be quickly configured with the <strong>set() <\/strong>function. This function also sets the default color palette, but that will be covered in more detail in the next section of the tutorial.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Drawing attractive figures are important. When making figures for yourself, as you explore a dataset, it\u2019s nice to have plots that are pleasant to look at. Visualizations are also central to communicating quantitative insights to an audience, and in that setting, it\u2019s even more necessary to have figures that catch the attention and draw a [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":6790,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[500],"tags":[],"class_list":["post-6744","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-science-using-python-tutorials"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/6744","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=6744"}],"version-history":[{"count":0,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/6744\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/6790"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=6744"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=6744"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=6744"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}