<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Matplotlib Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/category/matplotlib/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/category/matplotlib/</link>
	<description></description>
	<lastBuildDate>Sat, 30 Mar 2024 17:31:27 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Matplotlib Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/category/matplotlib/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Generate and Plot Random Samples from a Power-Law Distribution in Python?</title>
		<link>https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 30 Mar 2024 17:27:56 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<category><![CDATA[Statistics]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1669952</guid>

					<description><![CDATA[<p>To generate random samples from a power-law distribution in Python, use the numpy library for numerical operations and matplotlib for visualization. Here&#8217;s a minimal code example to generate and visualize random samples from a power-law distribution: First, we import the necessary libraries: numpy for generating the power-law distributed samples and matplotlib.pyplot for plotting. The a ... <a title="How to Generate and Plot Random Samples from a Power-Law Distribution in Python?" class="read-more" href="https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/" aria-label="Read more about How to Generate and Plot Random Samples from a Power-Law Distribution in Python?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/">How to Generate and Plot Random Samples from a Power-Law Distribution in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>To generate random samples from a <a href="https://blog.finxter.com/5-best-ways-to-create-logarithmic-y-axis-bins-in-python/" data-type="post" data-id="1664973">power-law distribution</a> in Python, use the <code>numpy</code> library for numerical operations and <code>matplotlib</code> for visualization. </p>



<ul class="wp-block-list">
<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4f1.png" alt="📱" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Computation</strong>: Specifically, you can use the <code>numpy.random.power</code> function, which draws samples from a power-law distribution with a specific exponent. </li>



<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4c8.png" alt="📈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Visualization</strong>: After generating the samples, it&#8217;s beneficial to visualize them in a log-log space to observe the characteristic straight-line behavior of power-law distributions. This visualization helps in understanding the distribution&#8217;s properties and confirming its power-law nature.</li>
</ul>



<p>Here&#8217;s a minimal code example to generate and visualize random samples from a power-law distribution:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="9" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt

# Parameters
a = 5  # Shape parameter
samples = 10000  # Number of samples

# Generate random samples
data = np.random.power(a, samples)

# Visualization in log-log space
counts, bins = np.histogram(data, bins=50)
bins_center = (bins[:-1] + bins[1:]) / 2
plt.loglog(bins_center, counts, marker='o', linestyle='none')

plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Power-law distribution in log-log space')
plt.show()</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="570" height="459" src="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-3.png" alt="" class="wp-image-1669956" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-3.png 570w, https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-3-300x242.png 300w" sizes="(max-width: 570px) 100vw, 570px" /></figure>
</div>


<p>First, we import the necessary libraries: <code>numpy</code> for generating the power-law distributed samples and <code>matplotlib.pyplot</code> for plotting.</p>



<p>The <code>a</code> parameter is the shape parameter of the power-law distribution, controlling the steepness of the distribution. The <code>samples</code> variable defines how many <a href="https://blog.finxter.com/5-secure-ways-to-generate-random-numbers-in-python/" data-type="post" data-id="1668905">random values we want to generate</a>.</p>



<p><code>np.random.power(a, samples)</code> generates an array of samples drawn from a power-law distribution with the shape parameter <code>a</code>.</p>



<p>To visualize the distribution in log-log space, we first compute the histogram of the data using <code>np.histogram</code>, which returns the counts and the bin edges.</p>



<p>We calculate the center of each bin for plotting purposes (<code>bins_center</code>) and then plot the histogram using <code>plt.loglog</code> to create a log-log plot. This is crucial for visualizing power-law distributions as they appear as straight lines in log-log plots.</p>



<p>Finally, we label the axes and show the plot with <code>plt.show()</code>.</p>



<h2 class="wp-block-heading">Creating Power Law Distribution Without Library Such As NumPy</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="570" height="459" src="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-4.png" alt="" class="wp-image-1669957" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-4.png 570w, https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-4-300x242.png 300w" sizes="(max-width: 570px) 100vw, 570px" /></figure>
</div>


<p class="has-global-color-8-background-color has-background">To create samples from a power-law distribution without a library, we use the inverse transform sampling method, where we <a href="https://blog.finxter.com/5-best-ways-to-generate-pseudo-random-numbers-in-python/" data-type="post" data-id="1669034">generate uniform random samples</a> and apply the inverse of the distribution&#8217;s cumulative distribution function (CDF) to these samples. This approach mathematically transforms uniformly distributed random numbers into numbers that follow the desired power-law distribution, based on the power-law&#8217;s specific characteristics and parameters.</p>



<p>Here&#8217;s the code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import random
import matplotlib.pyplot as plt

def generate_power_law_samples(alpha, size=1000, xmin=1):
    """Generate samples from a power-law distribution using the inverse transform sampling method."""
    samples = []
    for _ in range(size):
        u = random.random()  # Uniform random sample from 0 to 1
        x = xmin * (1 - u) ** (-1 / (alpha - 1))
        samples.append(x)
    return samples

def plot_rank_frequency(samples):
    """Plot samples in log-log space using rank-frequency."""
    # Sort samples in descending order
    sorted_samples = sorted(samples, reverse=True)
    # Generate ranks
    ranks = range(1, len(sorted_samples) + 1)
    # Plotting
    plt.loglog(ranks, sorted_samples, marker='o', linestyle='none')
    plt.xlabel('Rank')
    plt.ylabel('Sample Value')
    plt.title('Power-law distribution rank-frequency plot in log-log space')
    plt.show()

# Generate samples
alpha = 2.5  # Shape parameter of the power-law distribution
samples = generate_power_law_samples(alpha, 10000)

# Plot rank-frequency in log-log space
plot_rank_frequency(samples)
</pre>



<p></p>



<p>This code generates samples from a power-law distribution using the <code>generate_power_law_samples</code> function, as before.</p>



<p>The <code>plot_rank_frequency</code> function sorts the samples in descending order and then generates their ranks. In a rank-frequency plot, each point&#8217;s x-coordinate is its rank (i.e., its position in the sorted list), and its y-coordinate is the sample value itself.</p>



<p>We plot these points in a log-log space using <code>plt.loglog()</code>. This type of plot is useful for observing the power-law behavior of the distribution, where a linear relationship in log-log space indicates a power-law distribution.</p>



<p>The plot&#8217;s x-axis represents the ranks of the samples, and the y-axis represents the sample values, both on logarithmic scales. This visualization technique is effective for highlighting the characteristics of power-law distributions.</p>
<p>The post <a href="https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/">How to Generate and Plot Random Samples from a Power-Law Distribution in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Visualizing Wealth: Plotting the Net Worth of the World&#8217;s Richest in Log/Log Space</title>
		<link>https://blog.finxter.com/visualizing-wealth-plotting-the-net-worth-of-the-worlds-richest-in-log-log-space/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Mon, 25 Mar 2024 11:30:48 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1669872</guid>

					<description><![CDATA[<p>The distribution of wealth, especially when it comes to the ultra-wealthy, is a subject of immense fascination and study. It can reveal patterns and insights into economic structures, inequality, and financial dynamics at the highest levels. One of the most revealing ways to examine this distribution is through a log/log plot of the net worths ... <a title="Visualizing Wealth: Plotting the Net Worth of the World&#8217;s Richest in Log/Log Space" class="read-more" href="https://blog.finxter.com/visualizing-wealth-plotting-the-net-worth-of-the-worlds-richest-in-log-log-space/" aria-label="Read more about Visualizing Wealth: Plotting the Net Worth of the World&#8217;s Richest in Log/Log Space">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/visualizing-wealth-plotting-the-net-worth-of-the-worlds-richest-in-log-log-space/">Visualizing Wealth: Plotting the Net Worth of the World&#8217;s Richest in Log/Log Space</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>The distribution of wealth, especially when it comes to the ultra-wealthy, is a subject of immense fascination and study. It can reveal patterns and insights into economic structures, inequality, and financial dynamics at the highest levels.</p>



<p>One of the most revealing ways to examine this distribution is through a <strong>log/log plot of the net worths of the world&#8217;s richest individuals</strong>. Here&#8217;s how to visualize the net worth of the top 100 richest people using Python, providing a step-by-step guide to create a log/log space plot.</p>



<h2 class="wp-block-heading">Understanding the Data</h2>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4b0.png" alt="💰" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The <a href="https://www.businessinsider.in/thelife/personalities/news/top-100-richest-people-in-the-world-some-interesting-facts/articleshow/91069161.cms" target="_blank" rel="noreferrer noopener">dataset</a> consists of the net worths of the top 100 richest people in the world. This information is often available from financial news outlets and wealth-tracking websites. For the purpose of this demonstration, assume we have this data in a list where each value represents an individual&#8217;s net worth in billions of dollars.</p>



<p>Here&#8217;s a sample from the data: </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="701" height="748" src="https://blog.finxter.com/wp-content/uploads/2024/03/image-31.png" alt="" class="wp-image-1669874" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/image-31.png 701w, https://blog.finxter.com/wp-content/uploads/2024/03/image-31-281x300.png 281w" sizes="(max-width: 701px) 100vw, 701px" /></figure>
</div>


<h2 class="wp-block-heading">Why Log/Log Space?</h2>



<p>A log/log plot is particularly useful for data that spans several orders of magnitude, as it does with the world&#8217;s wealthiest individuals. This type of plot can help to linearize exponential relationships, making it easier to identify patterns that might not be apparent in a linear plot. For wealth distributions, which often follow a power law, log/log plots can highlight the underlying distribution&#8217;s scale-free nature.</p>



<h2 class="wp-block-heading">Preparing for the Plot</h2>



<p>Before plotting, ensure you have Python installed on your system along with the necessary libraries: Matplotlib for plotting and NumPy for numerical operations.</p>



<p>If you haven&#8217;t already, you can install these libraries using pip:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install matplotlib numpy</pre>



<h2 class="wp-block-heading">The Python Script</h2>



<p>First, import the necessary libraries:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import numpy as np</pre>



<p>Assuming you have the net worth data in a list named <code>net_worths</code> in billions of dollars, you can prepare your data. </p>



<p>For ease of reproducibility, I&#8217;ll include my list at the point of writing here: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">net_worths_float = [
    234.0, 156.0, 155.0, 126.0, 125.0, 124.0, 118.0, 117.0, 116.0, 116.0,
    87.8, 84.6, 82.4, 74.3, 72.6, 70.6, 69.6, 67.8, 63.2, 61.7, 61.6, 59.4,
    50.5, 50.5, 42.3, 41.3, 41.3, 40.0, 39.9, 39.1, 38.8, 37.0, 36.1, 36.0,
    35.2, 35.1, 34.2, 32.9, 32.0, 31.9, 31.9, 31.5, 30.1, 29.5, 29.3, 29.2,
    28.9, 28.5, 28.0, 27.9, 27.9, 27.7, 27.3, 27.1, 26.6, 26.5, 26.5, 25.9,
    25.1, 23.9, 23.9, 23.4, 23.2, 23.2, 23.0, 22.6, 22.3, 22.1, 21.8, 21.6,
    21.5, 21.5, 21.4, 21.4, 21.3, 21.2, 20.6, 20.6, 20.4, 20.3, 19.9, 19.7,
    19.6, 19.1, 19.0, 18.9, 18.8, 18.8, 18.5, 18.5, 18.5, 18.5, 18.4, 17.7,
    17.6, 17.6, 17.5, 17.2, 17.2, 17.2
]</pre>



<p>If your data isn&#8217;t sorted, sort it in descending order:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">net_worths = sorted(net_worths, reverse=True)</pre>



<p>Next, create a rank for each individual based on their position in the <a href="https://blog.finxter.com/5-best-ways-to-sort-lists-in-python-by-a-particular-digit-count-in-elements/" data-type="post" data-id="1663918">sorted list</a>. The richest person gets rank 1, the second richest gets rank 2, and so on:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ranks = np.arange(1, len(net_worths) + 1)</pre>



<h2 class="wp-block-heading">Plotting the Data</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="664" src="https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1-1024x664.png" alt="" class="wp-image-1669875" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1-1024x664.png 1024w, https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1-300x195.png 300w, https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1-768x498.png 768w, https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1-1536x996.png 1536w, https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1.png 1701w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Now, you&#8217;re ready to plot the data in log/log space:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.figure(figsize=(10, 6))
plt.loglog(ranks, net_worths, marker='o', linestyle='-', color='b')
plt.xlabel('Rank (log scale)')
plt.ylabel('Net Worth in Billions (log scale)')
plt.title('Net Worth of the Top 100 Richest People (Log/Log Space)')
plt.grid(True, which="both", ls="--")
plt.show()</pre>



<p></p>



<p>This code snippet will generate a log/log plot of the net worths. The <code>loglog</code> function from Matplotlib is used to automatically scale both axes to a logarithmic scale. Markers are added for each point to clearly delineate the individual net worths, and a grid is added for better readability.</p>



<h2 class="wp-block-heading">Interpreting the Plot</h2>



<p class="has-global-color-8-background-color has-background">In the resulting plot, each point represents an individual&#8217;s net worth plotted against their rank. A straight line in a log/log plot indicates a power law distribution, common in wealth distributions and many natural phenomena. The slope of this line (if it appears roughly straight) can give you the power law&#8217;s exponent, offering deeper insights into the inequality of wealth distribution.</p>



<p>This visualization technique is not just limited to financial data; it can be applied to any dataset that spans multiple orders of magnitude and is suspected to follow a power law or similar distribution. Whether you&#8217;re a data scientist, economist, or simply a curious observer, plotting data in log/log space can unveil patterns and relationships that are not immediately visible in traditional linear plots.</p>



<h2 class="wp-block-heading">Follow Up Analysis</h2>



<p>For instance, you can examine the cumulative net worth as people are sampled from this distribution: </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="652" src="https://blog.finxter.com/wp-content/uploads/2024/03/c4392eaa-f54f-4b24-b663-0d1364647d84-1024x652.png" alt="" class="wp-image-1669876" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/c4392eaa-f54f-4b24-b663-0d1364647d84-1024x652.png 1024w, https://blog.finxter.com/wp-content/uploads/2024/03/c4392eaa-f54f-4b24-b663-0d1364647d84-300x191.png 300w, https://blog.finxter.com/wp-content/uploads/2024/03/c4392eaa-f54f-4b24-b663-0d1364647d84-768x489.png 768w, https://blog.finxter.com/wp-content/uploads/2024/03/c4392eaa-f54f-4b24-b663-0d1364647d84-1536x979.png 1536w, https://blog.finxter.com/wp-content/uploads/2024/03/c4392eaa-f54f-4b24-b663-0d1364647d84.png 1728w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Also, check out our Finxter article:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://blog.finxter.com/8-millionaire-tips-to-reach-financial-freedom-as-a-coder/"><img loading="lazy" decoding="async" width="952" height="632" src="https://blog.finxter.com/wp-content/uploads/2024/03/image-92.png" alt="" class="wp-image-1669878" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/image-92.png 952w, https://blog.finxter.com/wp-content/uploads/2024/03/image-92-300x199.png 300w, https://blog.finxter.com/wp-content/uploads/2024/03/image-92-768x510.png 768w" sizes="auto, (max-width: 952px) 100vw, 952px" /></a></figure>
</div>


<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/8-millionaire-tips-to-reach-financial-freedom-as-a-coder/">8 Millionaire Tips to Reach Financial Freedom as a Coder</a></p>
<p>The post <a href="https://blog.finxter.com/visualizing-wealth-plotting-the-net-worth-of-the-worlds-richest-in-log-log-space/">Visualizing Wealth: Plotting the Net Worth of the World&#8217;s Richest in Log/Log Space</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Matplotlib Colors: A Comprehensive Guide for Effective Visualization</title>
		<link>https://blog.finxter.com/matplotlib-colors-a-comprehensive-guide-for-effective-visualization/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Tue, 14 Nov 2023 19:58:33 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1653046</guid>

					<description><![CDATA[<p>Here&#8217;s a minimal example of using colors in Matplotlib. This example creates a simple line plot with a specified color: In this minimal code example, plt.plot(x, y, color='red') creates a line plot of x versus y, with the line color set to red. You can replace 'red' with other color names like 'blue', 'green', etc., ... <a title="Matplotlib Colors: A Comprehensive Guide for Effective Visualization" class="read-more" href="https://blog.finxter.com/matplotlib-colors-a-comprehensive-guide-for-effective-visualization/" aria-label="Read more about Matplotlib Colors: A Comprehensive Guide for Effective Visualization">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/matplotlib-colors-a-comprehensive-guide-for-effective-visualization/">Matplotlib Colors: A Comprehensive Guide for Effective Visualization</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Here&#8217;s a minimal example of using colors in Matplotlib. This example creates a simple line plot with a specified color:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

# Plotting the line with a specific color, e.g., 'red'
plt.plot(x, y, color='red')

# Displaying the plot
plt.show()
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="587" height="439" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-80.png" alt="" class="wp-image-1653060" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-80.png 587w, https://blog.finxter.com/wp-content/uploads/2023/11/image-80-300x224.png 300w" sizes="auto, (max-width: 587px) 100vw, 587px" /></figure>
</div>


<p>In this minimal code example, <code>plt.plot(x, y, color='red')</code> creates a line plot of <code>x</code> versus <code>y</code>, with the line color set to red. You can replace <code>'red'</code> with other color names like <code>'blue'</code>, <code>'green'</code>, etc., or use color codes (e.g., <code>'#FF5733'</code> for a specific shade of orange).</p>



<p>Let&#8217;s explore Matplotlib&#8217;s amazing color functionality further! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Understanding Matplotlib Colors</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Different Color Formats in Matplotlib Python | Matplotlib Tutorial - Part 02" width="937" height="527" src="https://www.youtube.com/embed/AfKq_-5XTPM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h3 class="wp-block-heading">Basic Colors in Matplotlib</h3>



<p><a href="https://blog.finxter.com/python-matplotlib-makes-conways-game-of-life-come-alive/" data-type="post" data-id="972637">Matplotlib</a> is a popular data visualization library in Python, and colors play a crucial role in making these visualizations informative and visually appealing. With the right choice of colors, you can emphasize certain aspects of your data and make your plots more interpretable. In Matplotlib, you have access to a wide range of built-in colors to work with.</p>



<p>Some of the <a href="https://matplotlib.org/stable/gallery/color/named_colors.html">basic colors</a> in Matplotlib are red, green, blue, cyan, magenta, yellow, black, and white. These colors can be specified in a variety of ways, such as by their names or using RGB and RGBA values.</p>



<p>Here are some examples of how you can define colors in Matplotlib:</p>



<ul class="wp-block-list">
<li>By name: <code>'red'</code>, <code>'blue'</code>, <code>'green'</code></li>



<li>By RGB values: <code>(0.5, 0.2, 0.8)</code></li>



<li>By RGBA values: <code>(0.5, 0.2, 0.8, 0.5)</code></li>
</ul>



<h3 class="wp-block-heading">Matplotlib Recognizes Colors</h3>



<p><a href="https://matplotlib.org/stable/users/explain/colors/colors.html">Matplotlib recognizes different formats</a> to specify colors, which provides flexibility for you when customizing your visualizations. Transparency can also be added to these colors using the alpha value of an RGBA color.</p>



<p>Here&#8217;s a brief overview of some ways to specify colors in Matplotlib:</p>



<ul class="wp-block-list">
<li><strong>Named colors</strong>: E.g., <code>'coral'</code>, <code>'seagreen'</code>, <code>'royalblue'</code>.</li>



<li><strong>Hex color codes</strong>: E.g., <code>'#FF5733'</code>, <code>'#4D5656'</code>.</li>



<li><strong>RGB tuples</strong>: E.g., <code>(0.5, 0.8, 0.4)</code>.</li>



<li><strong>RGBA tuples</strong>: E.g., <code>(0.2, 0.7, 0.9, 0.6)</code>.</li>
</ul>



<p></p>



<h2 class="wp-block-heading">Working with RGB and Hex Colours</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="RGB-HexColors-Explained" width="937" height="703" src="https://www.youtube.com/embed/hhI4x6hx21s?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h3 class="wp-block-heading">RGB to Hex Conversion</h3>



<p>When working with colors in matplotlib, you might need to convert <strong>RGB</strong> values to <strong>Hex</strong> format. RGB colors are defined by a tuple of three values corresponding to the red, green, and blue components. For example, an RGB value can be represented as (0.1, 0.2, 0.5). To convert RGB colors to Hex values, you can use the <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.colors.to_hex.html"><code>matplotlib.colors.to_hex</code></a> function. Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.colors as mcolors

rgb_color = (0.1, 0.2, 0.5)
hex_color = mcolors.to_hex(rgb_color)
print(hex_color)
# #1a3380</pre>



<p>This code snippet will convert the RGB color <code>(0.1, 0.2, 0.5)</code> into its corresponding Hex value <code>'#1A3380'</code>.</p>



<h3 class="wp-block-heading">Specifying Colors in RGB and Hex</h3>



<p>In matplotlib, you can specify colors using both RGB and Hex values. When specifying colors as <strong>RGB</strong> or <strong>RGBA</strong> (red, green, blue, alpha) tuples, make sure to use float values in the closed interval [0, 1]. For example, you can use (0.1, 0.2, 0.5) for an RGB color or (0.1, 0.2, 0.5, 0.3) for an RGBA color with alpha transparency.</p>



<p>On the other hand, to specify colors in <strong>Hex</strong> format, use a string representing the hex RGB or RGBA value (e.g., <code>'#0f0f0f'</code> for an RGB hex color or <code>'#0f0f0f80'</code> for an RGBA hex color). The Hex string is case-insensitive.</p>



<p>Here&#8217;s a simple example of how to create a scatter plot while specifying colors in RGB and Hex formats:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Specifying colors in RGB and Hex
colors = [
    (0.1, 0.2, 0.5),  # RGB color
    '#FF5733',        # Hex color
    (1, 0, 0, 0.5),   # RGBA color
    '#0f0f0f80'       # RGBA Hex color
]

# Creating a scatter plot
for i, color in enumerate(colors):
    plt.scatter(x[i], y[i], color=color, label=color)

plt.legend()
plt.show()
</pre>



<p>Output:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="430" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-74-1024x430.png" alt="" class="wp-image-1653047" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-74-1024x430.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/11/image-74-300x126.png 300w, https://blog.finxter.com/wp-content/uploads/2023/11/image-74-768x323.png 768w, https://blog.finxter.com/wp-content/uploads/2023/11/image-74.png 1178w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h2 class="wp-block-heading">Using Named Colors and XKCD Colors</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Seaborn Color Palette Basics | Using named and custom color palettes in Python seaborn" width="937" height="527" src="https://www.youtube.com/embed/2wRHBodrWuY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>In matplotlib, you have access to a wide range of <a href="https://matplotlib.org/stable/gallery/color/named_colors.html">named colors</a> and <a href="https://matplotlib.org/stable/users/explain/colors/colors.html">XKCD colors</a> to create visually appealing and informative plots.</p>



<p><strong>Named colors</strong> are predefined colors with unique names, making it convenient for you to apply them in your plots. You can use basic color names such as <code>'blue'</code>, <code>'green'</code>, <code>'red'</code>, <code>'cyan'</code>, <code>'magenta'</code>, <code>'yellow'</code>, <code>'black'</code>, and <code>'white'</code>. Matplotlib library also supports a more extensive set of named colors, allowing you to choose from over 1200+ options. To work with named colors, simply use their names as the color parameter in your plot.</p>



<p><strong>XKCD colors</strong> were introduced based on a user survey conducted by the webcomic XKCD. These colors offer an even more diverse palette, with almost 95 of the 148 X11/CSS4 color names making an appearance in the XKCD color survey. Note that the color values for the X11/CSS4 and XKCD palettes may differ, with only <code>'black'</code>, <code>'white'</code>, and <code>'cyan'</code> being identical.</p>



<p>When creating your plots, you can combine both named and XKCD colors to enhance visual appeal:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi)
y = np.sin(x)

# Using named color
plt.plot(x, y, color='blue')

# Using XKCD color
plt.plot(x, y, color='xkcd:sea green')

plt.show()</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="592" height="459" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-75.png" alt="" class="wp-image-1653048" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-75.png 592w, https://blog.finxter.com/wp-content/uploads/2023/11/image-75-300x233.png 300w" sizes="auto, (max-width: 592px) 100vw, 592px" /></figure>
</div>


<p>Remember, when using XKCD colors, prefix the color name with <code>'xkcd:'</code>, as in <code>'xkcd:gray'</code>.</p>



<p>Explore and experiment with various <a href="https://matplotlib.org/stable/gallery/color/named_colors.html">named colors</a> and <a href="https://matplotlib.org/stable/users/explain/colors/colors.html">XKCD colors</a> in your matplotlib plots to customize them according to your needs. Choosing the right color combination not only makes your plots visually pleasing but also helps in conveying the information more effectively to your audience.</p>



<h2 class="wp-block-heading">Delving into Colormaps</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="701" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-40-1024x701.jpeg" alt="" class="wp-image-1653049" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-40-1024x701.jpeg 1024w, https://blog.finxter.com/wp-content/uploads/2023/11/image-40-300x205.jpeg 300w, https://blog.finxter.com/wp-content/uploads/2023/11/image-40-768x525.jpeg 768w, https://blog.finxter.com/wp-content/uploads/2023/11/image-40.jpeg 1216w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">Standard and Custom Colormaps</h3>



<p>In Matplotlib, you have access to a wide variety of <a href="https://matplotlib.org/stable/users/explain/colors/colormaps.html">built-in colormaps</a> that can be easily utilized for visualizing your data. Some popular colormaps include <strong>viridis</strong>, <strong>plasma</strong>, and <strong>inferno</strong>. To use a colormap, simply import the <code>matplotlib.cm</code> module as <code>cm</code> and then choose from the available colormaps.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.cm as cm
custom_colormap = cm.viridis
</pre>



<p>However, sometimes you may want to create a custom colormap that matches your specific needs. In this case, you can create your own colormap using the <code>LinearSegmentedColormap.from_list()</code> method. It requires a list of RGB tuples, defining the mixture of colors from 0 to 1.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from matplotlib.colors import LinearSegmentedColormap

colors = [(0, 0, 1), (0, 1, 1), (1, 1, 0), (1, 0, 0)]
custom_colormap = LinearSegmentedColormap.from_list("my_colormap", colors)
</pre>



<h3 class="wp-block-heading">Hot and Cold Colormaps</h3>



<p>A special subset of colormaps, known as hot and cold colormaps, are particularly useful when visualizing data with temperature-like values. These colormaps help to emphasize the contrast between low and high values in your data. Examples of hot colormaps are <strong>hot</strong>, <strong>autumn</strong>, and <strong>YlOrRd</strong>. Cold colormaps include <strong>cool</strong>, <strong>winter</strong>, and <strong>PuBu</strong>.</p>



<p>When working with <code>numpy</code> arrays (<code>np</code>), you can easily apply a colormap to your data. By first normalizing your data, you ensure that the colormap maps to the full range of values in your dataset.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

colors = [(0, 0, 1), (0, 1, 1), (1, 1, 0), (1, 0, 0)]
custom_colormap = LinearSegmentedColormap.from_list("my_colormap", colors)

data = np.random.rand(10, 10)
norm_data = (data - data.min()) / (data.max() - data.min())

fig, ax = plt.subplots()
im = ax.imshow(norm_data, cmap=custom_colormap)
plt.colorbar(im)
plt.show()
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="430" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-76-1024x430.png" alt="" class="wp-image-1653050" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-76-1024x430.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/11/image-76-300x126.png 300w, https://blog.finxter.com/wp-content/uploads/2023/11/image-76-768x323.png 768w, https://blog.finxter.com/wp-content/uploads/2023/11/image-76.png 1190w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p></p>



<h2 class="wp-block-heading">Matplotlib Pyplot and Its Color Utilities</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="701" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-41-1024x701.jpeg" alt="" class="wp-image-1653051" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-41-1024x701.jpeg 1024w, https://blog.finxter.com/wp-content/uploads/2023/11/image-41-300x205.jpeg 300w, https://blog.finxter.com/wp-content/uploads/2023/11/image-41-768x525.jpeg 768w, https://blog.finxter.com/wp-content/uploads/2023/11/image-41.jpeg 1216w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">Aqua and Other Unique Colors in Pyplot</h3>



<p>Matplotlib provides a diverse selection of colors, including unique ones like <a href="https://matplotlib.org/stable/users/explain/colors/colors.html">Aqua</a>. You can easily incorporate these colors into your plots to make them more visually appealing. </p>



<p>For instance, you can set an Aqua-colored line in your plot by specifying <code>c='aqua'</code> as a keyword argument when plotting with <code>plt.plot()</code>. You&#8217;ll find that it&#8217;s simple to experiment with different colors and create visually striking charts to enhance your data visualization.</p>



<h3 class="wp-block-heading">Working with Labels and Titles</h3>



<p>Adding labels and titles is essential to provide context and improve the readability of your plots. With Matplotlib&#8217;s <code>pyplot</code> (usually imported as <code>plt</code>), you can easily add titles and labels to your plots. To set a title for your plot, use the <code>plt.title()</code> function and pass in a string that describes the main topic of the plot. For example, <code>plt.title("My Aqua-colored Line Plot")</code> will display a title at the top of the plot.</p>



<p>Use <code>plt.xlabel()</code> and <code>plt.ylabel()</code> functions to label the x-axis and y-axis respectively. Provide a string describing the quantities being plotted along each axis, and the labels will appear next to the corresponding axis.</p>



<h2 class="wp-block-heading">Color Specification Conversions in Matplotlib</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="701" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-42-1024x701.jpeg" alt="" class="wp-image-1653052" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-42-1024x701.jpeg 1024w, https://blog.finxter.com/wp-content/uploads/2023/11/image-42-300x205.jpeg 300w, https://blog.finxter.com/wp-content/uploads/2023/11/image-42-768x525.jpeg 768w, https://blog.finxter.com/wp-content/uploads/2023/11/image-42.jpeg 1216w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>In Matplotlib, you can easily convert colors between different formats using built-in functions to ensure consistent handling of colors throughout your visualizations. Here are some of the key functions for color specification conversions:</p>



<ul class="wp-block-list">
<li><strong><code>to_rgba</code></strong>: This function allows you to convert a color or sequence of colors to RGBA format. It accepts a variety of input color formats (e.g., string, RGB tuple, or RGBA tuple), and normalizes the resulting RGBA values to a range of 0 to 1.</li>



<li><strong><code>to_rgba_array</code></strong>: Like the <code>to_rgba</code> function, this one converts a set of colors to RGBA format, but it does so for an entire array of colors in a single step. This is particularly useful when you&#8217;re working with colormaps or a large collection of colors.</li>



<li><strong><code>rgb_to_hsv</code></strong>: This function allows you to convert a set of RGB colors to the hue, saturation, and value (HSV) color space. This conversion can be useful for creating custom colormaps or color functions that take advantage of the HSV representation, which can be more intuitive when dealing with color palettes.</li>
</ul>



<p>Here&#8217;s an example of using these color conversion functions in your code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.colors as mcolors

# Convert a single color to RGBA format
color_rgba = mcolors.to_rgba('blue')

# Convert a list of colors to an RGBA array
color_list = ['red', 'green', 'blue']
color_rgba_array = mcolors.to_rgba_array(color_list)

# Convert a list of RGB colors to HSV format
rgb_colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
hsv_colors = mcolors.rgb_to_hsv(rgb_colors)
</pre>



<p>By understanding and utilizing these color specification conversion functions in Matplotlib, you can achieve greater control over your data visualizations and ensure that your colors are represented consistently across various color formats.</p>



<h2 class="wp-block-heading">Manipulating CSS4 and Tableau Colors</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="701" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-43-1024x701.jpeg" alt="" class="wp-image-1653053" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-43-1024x701.jpeg 1024w, https://blog.finxter.com/wp-content/uploads/2023/11/image-43-300x205.jpeg 300w, https://blog.finxter.com/wp-content/uploads/2023/11/image-43-768x525.jpeg 768w, https://blog.finxter.com/wp-content/uploads/2023/11/image-43.jpeg 1216w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">Introduction to CSS4 Colors</h3>



<p>With Matplotlib, you can tap into the power of CSS4 colors to enhance your data visualizations. CSS4 colors are a standardized set of over <a href="https://matplotlib.org/stable/gallery/color/named_colors.html">140 named colors</a> that can be used in web design, and they are also available in Matplotlib for creating vibrant and meaningful plots.</p>



<p>To use CSS4 colors, simply refer to the color by its name (case-insensitive) when specifying a color for a plot. For example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6], color='darkorchid')
plt.show()
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="592" height="449" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-77.png" alt="" class="wp-image-1653054" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-77.png 592w, https://blog.finxter.com/wp-content/uploads/2023/11/image-77-300x228.png 300w" sizes="auto, (max-width: 592px) 100vw, 592px" /></figure>
</div>


<p>This code snippet will generate a line plot with a <code>darkorchid</code> color. By exploring the <a href="https://matplotlib.org/stable/gallery/color/named_colors.html">list of named CSS4 colors</a>, you can find the perfect color for your visualization needs.</p>



<h3 class="wp-block-heading">Understanding Tableau Colors</h3>



<p>Tableau is a powerful data visualization tool that offers its own set of colors, known as the Tableau palette. The Tableau color palette is designed to be visually appealing and colorblind-friendly. In Matplotlib, you can access the Tableau colors by applying the <code>tableau-colorblind10</code> style:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

plt.style.use('tableau-colorblind10')
</pre>



<p>Once you have applied this style, Matplotlib will use the colors from the Tableau palette automatically for your plots. If you need to access a specific color from the palette, you can create a <a href="https://docs.python.org/3/library/stdtypes.html#dict">dictionary</a> of Tableau colors using their index positions:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tableau_colors = {
    0: '#1f77b4',
    1: '#ff7f0e',
    2: '#2ca02c',
    3: '#d62728',
    4: '#9467bd',
    5: '#8c564b',
    6: '#e377c2',
    7: '#7f7f7f',
    8: '#bcbd22',
    9: '#17becf'
}

color = tableau_colors[0]  # Access the first tableau color
</pre>



<p></p>



<h2 class="wp-block-heading">Working with Grayscale and Transparency</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="701" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-44-1024x701.jpeg" alt="" class="wp-image-1653055" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-44-1024x701.jpeg 1024w, https://blog.finxter.com/wp-content/uploads/2023/11/image-44-300x205.jpeg 300w, https://blog.finxter.com/wp-content/uploads/2023/11/image-44-768x525.jpeg 768w, https://blog.finxter.com/wp-content/uploads/2023/11/image-44.jpeg 1216w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">Grayscale in Matplotlib</h3>



<p class="has-global-color-8-background-color has-background">In Matplotlib, you can easily work with grayscale images. To display an image in grayscale, you can employ the <code><a href="https://blog.finxter.com/how-to-display-an-image-as-grayscale-in-python-matplotlib/" data-type="post" data-id="27875">imshow()</a></code> function. When reading an image using the <a href="https://blog.finxter.com/how-to-get-the-size-of-an-image-with-pil-in-python/" data-type="post" data-id="362009">PIL (Python Imaging Library)</a> library, you can convert it to grayscale with the <code>convert("L")</code> method. </p>



<p>For example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from PIL import Image
import matplotlib.pyplot as plt

image = Image.open(file).convert("L")
plt.imshow(image, cmap="gray")
plt.show()
</pre>



<p>This code snippet will display the image in grayscale using the <code>gray</code> color map.</p>



<h3 class="wp-block-heading">Transparency and Alpha Channel</h3>



<p>Transparency is another useful feature to work with in Matplotlib. The alpha channel determines the transparency level of an element. Alpha values range from 0 (completely transparent) to 1 (completely opaque).</p>



<p>You can set the alpha values for various elements, such as text, lines, or patches. For example, when creating a plot with a semi-transparent orange rectangle, you can adjust the alpha value:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.patches as patches

rect = patches.Rectangle((0.5, 0.5), 1, 1, linewidth=1, edgecolor='r', facecolor='orange', alpha=0.8)
ax.add_patch(rect)
plt.show()
</pre>



<p>In this example, the orange rectangle&#8217;s transparency is controlled by setting the <code>alpha</code> parameter to 0.8. Remember to keep your plots clear and understandable when using transparency with different elements.</p>



<h2 class="wp-block-heading">Using Matplotlib to Create Scatter Plots and Colorbars</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="701" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-45-1024x701.jpeg" alt="" class="wp-image-1653056" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-45-1024x701.jpeg 1024w, https://blog.finxter.com/wp-content/uploads/2023/11/image-45-300x205.jpeg 300w, https://blog.finxter.com/wp-content/uploads/2023/11/image-45-768x525.jpeg 768w, https://blog.finxter.com/wp-content/uploads/2023/11/image-45.jpeg 1216w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>In this section, we will discuss how you can use Matplotlib to create scatter plots and colorbars in your data visualizations. By the end of this section, you will be able to confidently create scatter plots and colorbars using the Matplotlib library.</p>



<h3 class="wp-block-heading">Creating Scatter Plots</h3>



<p>Scatter plots are widely used to visualize the relationships between two continuous data features. With Matplotlib, creating a scatter plot is as simple as using the <code>scatter()</code> function. For example, to create a basic scatter plot with random data points, you can use the following code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)
y = np.random.rand(100)

plt.scatter(x, y)
plt.show()
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="578" height="441" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-78.png" alt="" class="wp-image-1653057" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-78.png 578w, https://blog.finxter.com/wp-content/uploads/2023/11/image-78-300x229.png 300w" sizes="auto, (max-width: 578px) 100vw, 578px" /></figure>
</div>


<p>But what if you want to display multiple sets of data points, each with a different color? You can simply call the <code>scatter()</code> function multiple times before <code>plt.show()</code> and set the <code>color</code> parameter to a color of your choice:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.scatter(x1, y1, color='red')
plt.scatter(x2, y2, color='blue')
</pre>



<p>Find more details on creating different scatter plots <a href="https://stackoverflow.com/questions/12236566/setting-different-color-for-each-series-in-scatter-plot">here</a>.</p>



<h3 class="wp-block-heading">Building Colorbars</h3>



<p class="has-global-color-8-background-color has-background">Colorbars help in conveying additional information about your data points by assigning colors based on a third variable or their value. To create colorbars with your scatter plot, you need to set the <code>c</code> parameter in the <code>scatter()</code> function, which represents the data points&#8217; colors, and then use the <code>colorbar()</code> function:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)
y = np.random.rand(100)

c_values = np.random.rand(100)
plt.scatter(x, y, c=c_values, cmap='viridis')
plt.colorbar()
plt.show()
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="562" height="439" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-79.png" alt="" class="wp-image-1653058" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-79.png 562w, https://blog.finxter.com/wp-content/uploads/2023/11/image-79-300x234.png 300w" sizes="auto, (max-width: 562px) 100vw, 562px" /></figure>
</div>


<p>In the above example, the colors are set according to the <code>c_values</code> array, using the chosen colormap <code>viridis</code>. You can find more details on adding colorbars to your scatter plots <a href="https://stackoverflow.com/questions/6063876/matplotlib-colorbar-for-scatter">here</a>.</p>



<p></p>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="701" src="https://blog.finxter.com/wp-content/uploads/2023/11/image-46-1024x701.jpeg" alt="" class="wp-image-1653059" srcset="https://blog.finxter.com/wp-content/uploads/2023/11/image-46-1024x701.jpeg 1024w, https://blog.finxter.com/wp-content/uploads/2023/11/image-46-300x205.jpeg 300w, https://blog.finxter.com/wp-content/uploads/2023/11/image-46-768x525.jpeg 768w, https://blog.finxter.com/wp-content/uploads/2023/11/image-46.jpeg 1216w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">How do I specify a color in Matplotlib using RGB?</h3>



<p>To specify a color using RGB values in Matplotlib, you can use the tuple format <code>(r, g, b)</code>, where <code>r</code>, <code>g</code>, and <code>b</code> are floating-point numbers between 0 and 1 representing the intensity of red, green, and blue, respectively. For example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.plot(x, y, color=(0.5, 0.2, 0.8))
</pre>



<p>This will create a plot with a custom color that has 50% red, 20% green, and 80% blue.</p>



<h3 class="wp-block-heading">What are the default color cycles in Matplotlib?</h3>



<p>Matplotlib uses a default color cycle that is applied to plot elements like lines, markers, and labels. The default cycle includes the following colors, specified with single character shorthand:</p>



<ul class="wp-block-list">
<li><code>b</code>: blue</li>



<li><code>g</code>: green</li>



<li><code>r</code>: red</li>



<li><code>c</code>: cyan</li>



<li><code>m</code>: magenta</li>



<li><code>y</code>: yellow</li>



<li><code>k</code>: black</li>



<li><code>w</code>: white</li>
</ul>



<p>These colors will be used in the order specified when plotting multiple elements in a single plot.</p>



<h3 class="wp-block-heading">How do I convert a hex color to RGB in Matplotlib?</h3>



<p>In Matplotlib, you can convert a hex color to RGB by using the <code>matplotlib.colors.hex2color</code> function. Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.colors as mcolors
hex_color = "#32a852"
rgb_color = mcolors.hex2color(hex_color)
</pre>



<p>This will convert the hex color <code>#32a852</code> to its corresponding RGB tuple <code>(0.196, 0.658, 0.322)</code>.</p>



<h3 class="wp-block-heading">How can I create a custom color map in Matplotlib?</h3>



<p>To create a custom color map in Matplotlib, you can use the <code>matplotlib.colors.LinearSegmentedColormap</code> class. First, define a dictionary that maps the color channel (red, green, or blue) to a list of segments. Each segment is a tuple with three values: <code>(x, y1, y2)</code>, where <code>x</code> is a position between 0 and 1, and <code>y1</code> and <code>y2</code> are color intensities. Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
cmap_data = {
    'red': [(0.0, 0.0, 0.0), (1.0, 1.0, 1.0)],
    'green': [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0)],
    'blue': [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0)],
}
custom_cmap = mcolors.LinearSegmentedColormap('my_cmap', cmap_data)
</pre>



<p>This will create a custom color map that transitions from black to red.</p>



<h3 class="wp-block-heading">What are the available color palettes in Python?</h3>



<p>There are several color palettes available in Python, mainly provided by libraries like Matplotlib and Seaborn. In Matplotlib, you can access a comprehensive <a href="https://matplotlib.org/stable/gallery/color/named_colors.html">list of named colors</a> that includes color names from the CSS specification, X11 colors, and more. In Seaborn, you have access to a variety of color palettes such as qualitative, sequential, and diverging. You can use these palettes in either library, or even create your own custom palettes to suit your needs.</p>



<h3 class="wp-block-heading">How do I use color names in Matplotlib plots?</h3>



<p>Matplotlib supports using color names directly in your plot code. To utilize a color by its name, simply provide the name as a string for the <code>color</code> parameter when plotting. Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.plot(x, y, color='darkviolet')
</pre>



<p>This will create a plot with a line colored in <code>darkviolet</code>.</p>
<p>The post <a href="https://blog.finxter.com/matplotlib-colors-a-comprehensive-guide-for-effective-visualization/">Matplotlib Colors: A Comprehensive Guide for Effective Visualization</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Solved a Real-World Problem Using Monte Carlo Simulation</title>
		<link>https://blog.finxter.com/how-i-solved-a-real-world-problem-using-monte-carlo-simulation/</link>
		
		<dc:creator><![CDATA[Jonathan Okah]]></dc:creator>
		<pubDate>Thu, 27 Jul 2023 18:56:03 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1529271</guid>

					<description><![CDATA[<p>In this project, you are taking the role of a data analyst. Your client, a large retail outlet has been running an affiliate marketing program in an effort to increase its sales. You are tasked to come up with a predictive model to predict how much should be budgeted for sales commission for the following ... <a title="How I Solved a Real-World Problem Using Monte Carlo Simulation" class="read-more" href="https://blog.finxter.com/how-i-solved-a-real-world-problem-using-monte-carlo-simulation/" aria-label="Read more about How I Solved a Real-World Problem Using Monte Carlo Simulation">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-solved-a-real-world-problem-using-monte-carlo-simulation/">How I Solved a Real-World Problem Using Monte Carlo Simulation</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><em>In this project, you are taking the role of a data analyst. Your client, a large retail outlet has been running an affiliate marketing program in an effort to increase its sales. You are tasked to come up with a predictive model to predict how much should be budgeted for sales commission for the following year.</em></p>



<p>This is one of the projects you will likely come across as a data analyst. How do you go about solving this problem? No doubt, you will ask your client for more information. For example, data showing previous years’ commission payments, the number of sales representatives, and the company’s defined formula for calculating commissions.</p>



<p>For this project, we assumed that the only information at our disposal is a rate schedule showing the company’s formula for calculating commissions.</p>



<h2 class="wp-block-heading">Rates Schedule</h2>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Sales ($)</strong></td><td><strong>Rates</strong></td></tr><tr><td>1,000 – 100,000</td><td>3%</td></tr><tr><td>101,000 – 500,000</td><td>5%</td></tr><tr><td>501,000 – 1,000,000</td><td>10%</td></tr></tbody></table></figure>



<p>The table shows that the more sales, the higher the commission rate. Since we were neither given sales historical data nor the number of sales representatives, we are going to make a few assumptions.</p>



<h2 class="wp-block-heading">Basic Assumptions</h2>



<p>We will generate&nbsp; random sales data based on the following assumptions which are also based on the information from the rates schedule:</p>



<ol class="wp-block-list" type="1">
<li>Sales made cannot be below 1000 dollars.</li>



<li>Sales made are in thousands.</li>



<li>The company employed 500 persons for the affiliate marketing program.</li>



<li>Sales made by each individual cannot be more than 1 million dollars in a given year.</li>
</ol>



<p>With these assumptions, we are ready to generate random data.</p>



<p>Python’s random module is used to <a href="https://blog.finxter.com/python-how-to-generate-a-random-number-with-a-specific-amount-of-digits/" data-type="post" data-id="720085" target="_blank" rel="noreferrer noopener">generate random numbers</a>. We will use the <code><a href="https://blog.finxter.com/pandas-dataframe-sample-method/" data-type="post" data-id="343727" target="_blank" rel="noreferrer noopener">sample()</a></code> method which takes in a range of numbers and generate random data based on the length defined.</p>



<p>The parameters for the <code>range()</code> function are given as: <code><a href="https://blog.finxter.com/python-range-function/" data-type="post" data-id="18290" target="_blank" rel="noreferrer noopener">range(start, stop, step)</a></code> where:</p>



<ol class="wp-block-list" type="a">
<li><code>start</code>: The starting point. In our case, it is 1000 as we assumed that the sales amount cannot be below 1000 dollars.</li>



<li><code>stop</code>: The ending point. In our case, it is 1 million. We assumed that it won’t go beyond that.</li>



<li><code>step</code>: The number to skip to ensure that the data end with three zeros as given in the rates schedule.</li>
</ol>



<p>The <code>sample()</code> method takes another parameter that indicates the length of the random numbers. Remember that each randomly generated number represents the sales made by each individual. So, the length will be 500 to indicate the number of workforces employed by the company.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import random

sales = random.sample(range(1000, 1000000, 1000), 500)
</pre>



<p>Let’s load the data on a Pandas DataFrame.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd

data = pd.DataFrame({'Sales': sales})

data
0    986000
1    451000
2    487000
3    982000
4    194000
..      ...
495  761000
496  615000
497  786000
498  952000
499   82000

[500 rows x 1 columns]

data.Sales.min()
 2000

data.Sales.max()
986000
</pre>



<p>Now that we have our sales data. The next thing we have to do is to calculate the commission. The commission amount on the other hand is based on the rates. So, we need a way to assign rates for each sales representative based on sales made. A defined function will accomplish that.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def commissionRates(sales):
    if sales &lt;= 100000:
        return .03
    elif sales &lt;= 500000:
        return .05
    else:
        return .1
</pre>



<p>With this function defined, we can easily create the rates column using Pandas’ <code><a href="https://blog.finxter.com/the-pandas-apply-function/" data-type="post" data-id="37756" target="_blank" rel="noreferrer noopener">apply</a></code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data['Rates'] = data.Sales.apply(commissionRates)
data.head(10)

       Sales   Rates
0  986000   0.10
1  451000   0.05
2  487000   0.05
3  982000   0.10
4  194000   0.05
5  305000   0.05
6  154000   0.05
7  768000   0.10
8  685000   0.10
9  885000   0.10
</pre>



<p>The rates are applied according to the rates schedule given to us. To get the commission amount, it’s a matter of multiplying the rates by the sales amount.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data['Commission'] = data.Sales * data.Rates
data.tail(10)

          Sales     Rates  Commission
490  149000   0.05      7450.0
491  793000   0.10     79300.0
492  205000   0.05     10250.0
493  894000   0.10     89400.0
494  276000   0.05     13800.0
495  761000   0.10     76100.0
496  615000   0.10     61500.0
497  786000   0.10     78600.0
498  952000   0.10     95200.0
499   82000   0.03      2460.0
</pre>



<p>We now have the total commission amount of $ 21,831,140 to be paid to sales representatives.</p>



<h2 class="wp-block-heading">Monte Carlo Simulation</h2>



<p>Monte Carlo analysis is a useful tool for making predictions. It takes as an input, different random numbers and runs them several times to generate many probable outcomes. How do we apply it in our case?</p>



<p>We want to predict the commission amount to be budgeted for the coming year. The amount we realized was based on one single attempt or iteration. We can’t just conclude that this is the ideal amount until we run it several times up to 10,000 or more using different randomly generated data.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def simulate_commission(iterations):
    results = []
    for i in range(iterations):
    sales = random.sample(range(1000, 1000000, 1000), 500)
    data = pd.DataFrame({'Sales': sales})
    data['Rates'] = data.Sales.apply(commissionRates)
    data['Commission'] = data.Sales * data.Rates
    results.append(
        [
        data.Sales.sum().round(),
        data.Commission.sum().round(),
        ]
    )
    
    return results
</pre>



<p>We create a function that will perform the simulation based on the number of times chosen. We can try 1,000, 10,000 or even 50,000 times. In the end, we sum the sales and the commissions to be used for further analysis.</p>



<p>Let’s give it a try with 5000 simulations and load it on a <a href="https://blog.finxter.com/pandas-dataframe-object-a-beginners-guide/" data-type="post" data-id="1511689" target="_blank" rel="noreferrer noopener">Pandas DataFrame</a>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">results = simulate_commission(5000)
results = pd.DataFrame.from_records(results, columns=[‘Sales’, ‘Commission’])

results
          Sales        Commission
0     256137000  22305150.0
1     252466000  21865310.0
2     246516000  21478230.0
3     250821000  21669860.0
4     252750000  22314280.0
...         ...         ...
4995  253876000  22073200.0
4996  245326000  21089810.0
4997  248717000  21651090.0
4998  246074000  21105970.0
4999  251908000  21810780.0

results.describe().round()
                  
                  Sales   Commission
count       5000.0      5000.0
mean   250092538.0  21826489.0
std      4526122.0    523127.0
min    229959000.0  19379090.0
25%    247034250.0  21476432.0
50%    250058000.0  21816840.0
75%    253203250.0  22188120.0
max    266212000.0  23649430.0
</pre>



<p>After running 5000 simulations, the results show that the commission amount is between $19M and $23M with a mean of $21M. This is within our previous results. Let’s visualize this on a <a href="https://blog.finxter.com/matplotlib-histogram/" data-type="post" data-id="5485" target="_blank" rel="noreferrer noopener">histogram</a>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def currency(x, pos):
    if x >= 1e6:
        s = '${:1.1f}M'.format(x*1e-6)
    else:
        s = '${:1.0f}K'.format(x*1e-3)
    return s
</pre>



<p>Here, we are setting the function that will format the commission amount as it’s too large to be fitted on the chart. It will take the amount and the tick position as parameters. We will feed it into the <code>xaxis.set_major_formatter()</code> method to format the string.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot

fig, ax = plt.subplots()

ax.xaxis.set_major_formatter(currency)

results.Commission.plot(kind='hist', title='Commission Amount')

plt.grid()
plt.show()
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="714" height="401" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-393.png" alt="" class="wp-image-1529275" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-393.png 714w, https://blog.finxter.com/wp-content/uploads/2023/07/image-393-300x168.png 300w" sizes="auto, (max-width: 714px) 100vw, 714px" /></figure>
</div>


<p>Running the simulation 10,000 times produced the following result which is almost similar to the previous one.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="714" height="401" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-394.png" alt="" class="wp-image-1529276" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-394.png 714w, https://blog.finxter.com/wp-content/uploads/2023/07/image-394-300x168.png 300w" sizes="auto, (max-width: 714px) 100vw, 714px" /></figure>



<p>The mean is still between $21M and $22M, and the commission payment ranges between $19M and $24M.</p>



<p>These results no doubt give the managers of the retail outlet an estimate of how much should be budgeted for commission payment for the following year.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>We solved a real-world problem using Monte Carlo simulation – a tool used to gain a better understanding of distributions of probable outcomes. By calculating a formula multiple times using different random inputs, management can be able to make informed decisions.</p>



<p>This demonstration gives you an idea of how you can apply Monte Carlo simulation to solve more advanced problems.</p>
<p>The post <a href="https://blog.finxter.com/how-i-solved-a-real-world-problem-using-monte-carlo-simulation/">How I Solved a Real-World Problem Using Monte Carlo Simulation</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Towards Reverse Engineering Matplotlib Code From Images</title>
		<link>https://blog.finxter.com/towards-reverse-engineering-matplotlib-code-from-images/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sun, 23 Jul 2023 13:03:13 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Google Bard]]></category>
		<category><![CDATA[Large Language Model (LLM)]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1520001</guid>

					<description><![CDATA[<p>I tried a few helpful applications of Google Bards Image Recognition capabilities for coders. I don&#8217;t know about you but I often see beautiful plots (e.g., in research papers or data science reports) and wonder how I could recreate them. Well, Google Bard to the rescue! ✅ Reverse Engineer Exponential Plot in 2D First, let&#8217;s ... <a title="Towards Reverse Engineering Matplotlib Code From Images" class="read-more" href="https://blog.finxter.com/towards-reverse-engineering-matplotlib-code-from-images/" aria-label="Read more about Towards Reverse Engineering Matplotlib Code From Images">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/towards-reverse-engineering-matplotlib-code-from-images/">Towards Reverse Engineering Matplotlib Code From Images</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>I tried a few helpful applications of Google Bards Image Recognition capabilities for coders. I don&#8217;t know about you but I often see beautiful plots (e.g., in research papers or data science reports) and wonder how I could recreate them.</p>



<p>Well, Google Bard to the rescue! </p>



<h2 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Reverse Engineer Exponential Plot in 2D</h2>



<p>First, let&#8217;s try a simple exponential curve.</p>



<p><strong>Input Image:</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="613" height="459" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-293.png" alt="" class="wp-image-1520012" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-293.png 613w, https://blog.finxter.com/wp-content/uploads/2023/07/image-293-300x225.png 300w" sizes="auto, (max-width: 613px) 100vw, 613px" /></figure>
</div>


<p>I passed this chart along with the following prompt in Google Bard:</p>



<pre class="wp-block-preformatted"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9d1-200d-1f4bb.png" alt="🧑‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Prompt</strong>: <code>Reverse engineer the code leading to this graphic</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="791" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-295-1024x791.png" alt="" class="wp-image-1520014" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-295-1024x791.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/07/image-295-300x232.png 300w, https://blog.finxter.com/wp-content/uploads/2023/07/image-295-768x593.png 768w, https://blog.finxter.com/wp-content/uploads/2023/07/image-295.png 1191w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>So Google Bard suggests the following code to generate the graph in Python.</p>



<p><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f916.png" alt="🤖" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Bard Output Code:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import numpy as np

def exponential_function(x):
  return np.exp(x)

x_values = np.linspace(0, 10, 100)
y_values = exponential_function(x_values)

plt.plot(x_values, y_values)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Exponential Curve')
plt.show()
</pre>



<p>This code from Google Bard generates the following chart.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="601" height="444" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-294.png" alt="" class="wp-image-1520013" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-294.png 601w, https://blog.finxter.com/wp-content/uploads/2023/07/image-294-300x222.png 300w" sizes="auto, (max-width: 601px) 100vw, 601px" /></figure>
</div>


<p>Insane! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92f.png" alt="🤯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Google Bard figured out the exact exponential curve by looking at the input chart. </p>



<p>This is really advanced if you think about it. I was particularly impressed by the fact that Bard even got the function right leading to the chart &#8212; not only the rough code to plot a similar chart.</p>



<p>So if you needed one more proof of the deep intelligence of <a href="https://blog.finxter.com/the-evolution-of-large-language-models-llms-insights-from-gpt-4-and-beyond/" data-type="post" data-id="1267220" target="_blank" rel="noreferrer noopener">large language models (LLMs)</a> that&#8217;s way beyond the trivial probabilistic prediction of the next word or character, here it is.</p>



<p>Let&#8217;s try another more complex (higher-order) curve:</p>



<h2 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9d0.png" alt="🧐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Reverse Engineer Higher-Order Curve</h2>



<p>Now let&#8217;s use a higher-order cubic function plot and pass it into Google Bard to see if it can generate the code that produces it.</p>



<p><strong>Input Image:</strong></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="605" height="445" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-296.png" alt="" class="wp-image-1520015" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-296.png 605w, https://blog.finxter.com/wp-content/uploads/2023/07/image-296-300x221.png 300w" sizes="auto, (max-width: 605px) 100vw, 605px" /></figure>



<pre class="wp-block-preformatted"><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9d1-200d-1f4bb.png" alt="🧑‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Prompt</strong>: <code>Give me the code leading to this output</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="855" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-298-1024x855.png" alt="" class="wp-image-1520018" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-298-1024x855.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/07/image-298-300x251.png 300w, https://blog.finxter.com/wp-content/uploads/2023/07/image-298-768x642.png 768w, https://blog.finxter.com/wp-content/uploads/2023/07/image-298.png 1166w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Google Bard spits out the following code. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f916.png" alt="🤖" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Bard Output Code:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import numpy as np

# Create the data
x = np.linspace(-10, 10, 100)
y = x**2

# Plot the data
plt.plot(x, y)

# Add a title
plt.title('Plot of a Higher-Order Function')

# Add labels to the axes
plt.xlabel('X')
plt.ylabel('f(x)')

# Show the plot
plt.show()
</pre>



<p>This yields the following image:</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="605" height="449" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-297.png" alt="" class="wp-image-1520016" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-297.png 605w, https://blog.finxter.com/wp-content/uploads/2023/07/image-297-300x223.png 300w" sizes="auto, (max-width: 605px) 100vw, 605px" /></figure>



<p>Some things are correct, such as the x-axis and the labels. Other things are incorrect or imprecise such as the y-axis and the plot &#8212; even though it figured out that it&#8217;s a higher-order function.</p>



<p></p>



<h2 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 3D Normal Distribution</h2>



<p>Next, I tried a more complex 3D plot of a multivariate normal distribution. You can read my blog tutorial on how to do this <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-plot-a-3d-normal-distribution-in-python/" data-type="post" data-id="1518449" target="_blank">here</a>.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-to-plot-a-3d-normal-distribution-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-plot-a-3d-normal-distribution-in-python/" target="_blank" rel="noreferrer noopener">How to Plot a 3D Normal Distribution in Python?</a></p>



<p>This is the image I passed into Google Bard.</p>



<p><strong>Input Image:</strong></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="417" height="398" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-289-1.png" alt="" class="wp-image-1520009" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-289-1.png 417w, https://blog.finxter.com/wp-content/uploads/2023/07/image-289-1-300x286.png 300w" sizes="auto, (max-width: 417px) 100vw, 417px" /></figure>



<p>And the Bard prompt:</p>



<pre class="wp-block-preformatted"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9d1-200d-1f4bb.png" alt="🧑‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Prompt</strong>: <code>Reproduce the code that generates the image</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="819" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-291-1024x819.png" alt="" class="wp-image-1520007" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-291-1024x819.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/07/image-291-300x240.png 300w, https://blog.finxter.com/wp-content/uploads/2023/07/image-291-768x614.png 768w, https://blog.finxter.com/wp-content/uploads/2023/07/image-291.png 1191w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f916.png" alt="🤖" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Bard Output Code:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import plotly.graph_objects as go

fig = go.Figure(data=[go.Cone(
    x=[1, 2, 3],
    y=[1, 2, 3],
    z=[1, 2, 3],
    u=[1, 2, 3],
    v=[1, 1, 2],
    w=[4, 4, 1],
    showscale=False,
    hoverinfo="u+v+w+name",
)])

fig.update_layout(
    title="3D Cone Plot",
    scene=dict(
        camera=dict(
            eye=dict(x=-1.57, y=1.36, z=0.58),
        ),
        domain=dict(x=[0, 1]),
    ),
)

fig.show()
</pre>



<p>When I run the code, I get the following output:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="529" src="https://blog.finxter.com/wp-content/uploads/2023/07/image-292-1024x529.png" alt="" class="wp-image-1520011" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/image-292-1024x529.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/07/image-292-300x155.png 300w, https://blog.finxter.com/wp-content/uploads/2023/07/image-292-768x397.png 768w, https://blog.finxter.com/wp-content/uploads/2023/07/image-292.png 1099w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Fail. </p>



<p>While it captures that the plot is generated with Python and it contains a 3D plot (out of all things possible), it doesn&#8217;t produce the correct plot in that case.</p>



<h2 class="wp-block-heading">Putting It Together</h2>



<p>I&#8217;m very impressed with Google Bard&#8217;s capabilities, and I&#8217;m sure they will grow significantly over the next couple of months. Google Bard can already match the capabilities of an entry-level data scientist. </p>



<p>Soon you&#8217;ll be able to pass screenshots of arbitrary plots into it and let it generate the code for you. This is six-figure-per-year work currently done by advanced data scientists.</p>



<p>When I was still a researcher at University, I&#8217;d have done almost everything for such a tool &#8212; given that most research papers live and die by the high-quality plots they generate and most researchers and data scientists spend huge amounts of time figuring out how others have generated their stunning-looking plots.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/google-bard-detects-code-in-images-png-jpeg-webp/" data-type="URL" data-id="https://blog.finxter.com/google-bard-detects-code-in-images-png-jpeg-webp/" target="_blank" rel="noreferrer noopener">Google Bard Extracts Code From Images (PNG, JPEG, WebP)</a></p>
<p>The post <a href="https://blog.finxter.com/towards-reverse-engineering-matplotlib-code-from-images/">Towards Reverse Engineering Matplotlib Code From Images</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Plot a 3D Normal Distribution in Python?</title>
		<link>https://blog.finxter.com/how-to-plot-a-3d-normal-distribution-in-python/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 22 Jul 2023 20:50:42 +0000</pubDate>
				<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1518449</guid>

					<description><![CDATA[<p>To create a 3D surface plot of a bivariate normal distribution define two normally distributed random variables x and y, each with its own mean (mu_x, mu_y) and variance (variance_x, variance_y). The random variables are independent,the covariance between x and y is 0. Use the grid of (x, y) pairs to calculate the probability density ... <a title="How to Plot a 3D Normal Distribution in Python?" class="read-more" href="https://blog.finxter.com/how-to-plot-a-3d-normal-distribution-in-python/" aria-label="Read more about How to Plot a 3D Normal Distribution in Python?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-plot-a-3d-normal-distribution-in-python/">How to Plot a 3D Normal Distribution in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="has-global-color-8-background-color has-background">To create a 3D surface plot of a bivariate normal distribution define two normally distributed random variables <code>x</code> and <code>y</code>, each with its own mean (<code>mu_x</code>, <code>mu_y</code>) and variance (<code>variance_x</code>, <code>variance_y</code>). The random variables are independent,the covariance between <code>x</code> and <code>y</code> is 0. Use the grid of <code>(x, y)</code> pairs to calculate the <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Probability_density_function" data-type="URL" data-id="https://en.wikipedia.org/wiki/Probability_density_function" target="_blank">probability density function (pdf)</a> of this bivariate normal distribution at each point. </p>



<p>Here&#8217;s the code for copy and paste. I also added comments to explain what each part is doing: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
from mpl_toolkits.mplot3d import Axes3D

# define parameters for x and y distributions
mu_x = 0  # mean of x
variance_x = 3  # variance of x

mu_y = 0  # mean of y
variance_y = 15  # variance of y

# define a grid for x and y values
x = np.linspace(-10, 10, 500)  # generate 500 points between -10 and 10 for x
y = np.linspace(-10, 10, 500)  # generate 500 points between -10 and 10 for y
X, Y = np.meshgrid(x, y)  # create a grid for (x,y) pairs

# create an empty array of the same shape as X to hold the (x, y) coordinates
pos = np.empty(X.shape + (2,))

# fill the pos array with the x and y coordinates
pos[:, :, 0] = X  
pos[:, :, 1] = Y  

# create a multivariate normal distribution using the defined parameters
rv = multivariate_normal([mu_x, mu_y], [[variance_x, 0], [0, variance_y]])

# create a new figure for 3D plot
fig = plt.figure()

# add a 3D subplot to the figure
ax = fig.add_subplot(projection='3d')

# create a 3D surface plot of the multivariate normal distribution
ax.plot_surface(X, Y, rv.pdf(pos), cmap='viridis', linewidth=0)

# set labels for the axes
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

# display the 3D plot
plt.show()
</pre>



<p class="has-base-2-background-color has-background"><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></strong> <strong>Interactive</strong>: I also created a Google Colab Jupyter Notebook where you can plot it yourself. <a rel="noreferrer noopener" href="https://colab.research.google.com/drive/1RpLM8l0gEJq-MQm17oRG9p8wggcAkMv8?usp=sharing" data-type="URL" data-id="https://colab.research.google.com/drive/1RpLM8l0gEJq-MQm17oRG9p8wggcAkMv8?usp=sharing" target="_blank">Click here to open it in a new tab.</a></p>



<p>I went ahead and tried to anticipate some follow-up questions you may have on the code. Here they are: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f914.png" alt="🤔" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2753.png" alt="❓" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<h2 class="wp-block-heading">FAQ</h2>



<ol class="wp-block-list">
<li><strong>What is a multivariate normal distribution?</strong> This concept from probability theory and statistics extends the 1D normal distribution to multiple dimensions. The code uses a 2D or bivariate normal distribution.</li>



<li><strong>What does <code>np.linspace(-10, 10, 500)</code> do?</strong> This function generates 500 evenly spaced points from -10 to 10 over the interval. It&#8217;s used here to create a range of values for x and y. <a href="https://blog.finxter.com/np-linspace/" data-type="post" data-id="4876" target="_blank" rel="noreferrer noopener">I have written a detailed blog tutorial here (with video).</a></li>



<li><strong>What is <code>np.meshgrid(x, y)</code> used for?</strong> This function generates a two-dimensional grid of coordinates based on two one-dimensional arrays. In this case, it generates a grid of <code>(x, y)</code> pairs.</li>



<li><strong>What is the purpose of the <code>pos</code> array?</strong> The <code>pos</code> array is used to hold the coordinates of each point in the grid in a format suitable for use with the <code>multivariate_normal</code> probability density function. It&#8217;s a 3D array where the first two dimensions match the dimensions of the grid, and the third dimension has size 2 to hold the <code>x</code> and <code>y</code> coordinates.</li>



<li><strong>What does <code>rv.pdf(pos)</code> do?</strong> This function calculates the value of the probability density function (pdf) of the multivariate normal distribution at each point in the grid.</li>



<li><strong>What is <code>plot_surface</code> used for?</strong> This function is used to create a three-dimensional plot of the distribution. It takes as input the <code>x</code> and <code>y</code> coordinates and the pdf values at each point, generating a 3D surface plot.</li>



<li><strong>What is the purpose of <code>'cmap'</code> parameter in the <code>plot_surface</code> function?</strong> The &#8216;<code>cmap</code>&#8216; parameter is used to specify the color map for the plot. <code>'viridis'</code> is one of the predefined color maps in Matplotlib.</li>



<li><strong>Why is the covariance matrix diagonal?</strong> The covariance matrix is diagonal because the variables <code>x</code> and <code>y</code> are assumed to be independent in this bivariate distribution. Off-diagonal elements of the covariance matrix represent the covariance between different variables &#8211; these are zero if the variables are independent.</li>



<li><strong>What does <code>linewidth=0</code> do?</strong> The <code>linewidth</code> parameter in <code>plot_surface</code> specifies the line width for the edges of the surface polygons. Setting it to 0 removes these edges.</li>
</ol>



<p>Feel free to check out our full course on Matplotlib on the Finxter academy. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Academy</strong>: <a href="https://academy.finxter.com/university/matplotlib-a-guide-to-becoming-a-data-visualization-wizard/" data-type="URL" data-id="https://academy.finxter.com/university/matplotlib-a-guide-to-becoming-a-data-visualization-wizard/" target="_blank" rel="noreferrer noopener">Matplotlib &#8211; The Complete Guide to Becoming a Data Visualization Wizard</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-plot-a-3d-normal-distribution-in-python/">How to Plot a 3D Normal Distribution in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>(Fix) ValueError: Argument Z must be 2-dimensional</title>
		<link>https://blog.finxter.com/fix-valueerror-argument-z-must-be-2-dimensional/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 22 Jul 2023 18:28:25 +0000</pubDate>
				<category><![CDATA[Error]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1518406</guid>

					<description><![CDATA[<p>Problem Formulation The output when running this code is as follows Warning (from warnings module): File "C:\Users\xcent\Desktop\code.py", line 10 ax = fig.gca(projection='3d') MatplotlibDeprecationWarning: Calling gca() with keyword arguments was deprecated in Matplotlib 3.4. Starting two minor releases later, gca() will take no keyword arguments. The gca() function should only be used to get the current ... <a title="(Fix) ValueError: Argument Z must be 2-dimensional" class="read-more" href="https://blog.finxter.com/fix-valueerror-argument-z-must-be-2-dimensional/" aria-label="Read more about (Fix) ValueError: Argument Z must be 2-dimensional">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/fix-valueerror-argument-z-must-be-2-dimensional/">(Fix) ValueError: Argument Z must be 2-dimensional</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Problem Formulation</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import numpy as np


X = np.array([1, 2, 3])
Y = np.array([1, 2, 3])
Z = np.array([1, 2, 3])

fig = plt.figure()
ax = fig.gca(projection='3d')
surface = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

plt.show()</pre>



<p>The output when running this code is as follows</p>



<pre class="wp-block-preformatted"><code><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-contrast-3-color"><em>Warning (from warnings module):
  File "C:\Users\xcent\Desktop\code.py", line 10
    ax = fig.gca(projection='3d')
MatplotlibDeprecationWarning: Calling gca() with keyword arguments was deprecated in Matplotlib 3.4. Starting two minor releases later, gca() will take no keyword arguments. The gca() function should only be used to get the current axes, or if no axes exist, create new axes with default keyword arguments. To create a new axes with non-default arguments, use plt.axes() or plt.subplot().
Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 11, in &lt;module>
    surface = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)
  File "C:\Users\xcent\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\_api\deprecation.py", line 431, in wrapper
    return func(*inner_args, **inner_kwargs)
  File "C:\Users\xcent\AppData\Local\Programs\Python\Python39\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 1658, in plot_surface
    raise ValueError("Argument Z must be 2-dimensional.")</em></mark>
&#x1f449; <strong><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-accent-color">ValueError: Argument Z must be 2-dimensional.</mark></strong></code> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f914.png" alt="🤔" class="wp-smiley" style="height: 1em; max-height: 1em;" /></pre>



<h2 class="wp-block-heading">Solution</h2>



<p class="has-global-color-8-background-color has-background">The error message <code>ValueError: Argument Z must be 2-dimensional.</code> indicates that the <code>plot_surface</code> method requires a 2-dimensional array for the <code>Z</code> parameter. In the code above, I&#8217;m passing a 1-dimensional array <code>Z = np.array([1, 2, 3])</code>.</p>



<p>As for the deprecation warning, this is because the method <code>gca()</code> will no longer accept keyword arguments in future versions of <a rel="noreferrer noopener" href="https://blog.finxter.com/display-modify-and-save-images-with-matplotlib/" data-type="post" data-id="27129" target="_blank">Matplotlib</a>, so I should use a different method to create the axes.</p>



<p>Here&#8217;s a modified version of your code that should work correctly. This code creates a simple 3D surface where the Z values are simply the product of the X and Y values:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import numpy as np


X = np.array([[1, 2, 3]])
Y = np.array([[1], [2], [3]])
Z = X * Y

fig = plt.figure()
ax = plt.axes(projection='3d')
surface = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

plt.show()
</pre>



<p>In the fixed code, <code>X</code>, <code>Y</code>, and <code>Z</code> are all 2-dimensional arrays now. I made <code>X</code> and <code>Y</code> 2D by adding an extra set of brackets around their definitions. This creates arrays with shapes <code>(1,3)</code> and <code>(3,1)</code>, respectively. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Shape Example</strong>: A 2D array with shape <code>(1,3)</code> is like a single row with 3 columns, containing 3 elements. An array with shape <code>(3,1)</code> is like 3 rows with a single column each, a tall, thin structure with 3 elements.</p>



<p>When multiplied to create <code>Z</code>, they are broadcasted into two dimensions to create a <code>(3,3)</code> array.</p>



<p>Also, instead of using <code>gca()</code> to create the 3D axes, I have used the <code>plt.axes()</code> function with the <code>projection='3d'</code> keyword argument, as suggested by the deprecation warning.</p>
<p>The post <a href="https://blog.finxter.com/fix-valueerror-argument-z-must-be-2-dimensional/">(Fix) ValueError: Argument Z must be 2-dimensional</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How Do I Make a 3D Waterfall Plot with Colored Heights in Python?</title>
		<link>https://blog.finxter.com/how-do-i-make-a-3d-waterfall-plot-with-colored-heights-in-python/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 22 Jul 2023 15:20:32 +0000</pubDate>
				<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1518190</guid>

					<description><![CDATA[<p>To generate a 3D waterfall plot with colored heights create a 2D sine wave using the NumPy meshgrid() function, then apply a colormap to the heights using Matplotlib&#8217;s Normalize function. The plot_surface() function generates the 3D plot, while the color gradient is added using a ScalarMappable object. Here&#8217;s a code example for copy and paste: ... <a title="How Do I Make a 3D Waterfall Plot with Colored Heights in Python?" class="read-more" href="https://blog.finxter.com/how-do-i-make-a-3d-waterfall-plot-with-colored-heights-in-python/" aria-label="Read more about How Do I Make a 3D Waterfall Plot with Colored Heights in Python?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-do-i-make-a-3d-waterfall-plot-with-colored-heights-in-python/">How Do I Make a 3D Waterfall Plot with Colored Heights in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="has-global-color-8-background-color has-background">To generate a 3D waterfall plot with colored heights create a 2D sine wave using the NumPy <code>meshgrid()</code> function, then apply a colormap to the heights using Matplotlib&#8217;s <code>Normalize</code> function. The <code>plot_surface()</code> function generates the 3D plot, while the color gradient is added using a <code>ScalarMappable</code> object.</p>



<p>Here&#8217;s a code example for copy and paste: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

# Create the X, Y, and Z coordinate arrays. 
x = np.linspace(-5, 5, 101)
y = np.linspace(-5, 5, 101)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Create a surface plot and projected filled contour plot under it.
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

# Select Colormap
cmap = cm.viridis

# Norm for color mapping
norm = plt.Normalize(Z.min(), Z.max())

# Plot surface with color mapping
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=cmap(norm(Z)), alpha=0.9, linewidth=0)

# Add a color bar which maps values to colors
m = cm.ScalarMappable(cmap=cmap, norm=norm)
m.set_array(Z)
fig.colorbar(m)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
</pre>



<p>If you run this code in your Python shell, you&#8217;ll get a beautiful interactive 3D waterfall plot:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="800" height="600" src="https://blog.finxter.com/wp-content/uploads/2023/07/output.jpeg" alt="" class="wp-image-1518244" srcset="https://blog.finxter.com/wp-content/uploads/2023/07/output.jpeg 800w, https://blog.finxter.com/wp-content/uploads/2023/07/output-300x225.jpeg 300w, https://blog.finxter.com/wp-content/uploads/2023/07/output-768x576.jpeg 768w" sizes="auto, (max-width: 800px) 100vw, 800px" /></figure>
</div>


<p>In your case you&#8217;ll probably need to replace the data with your own. Feel free to check out our guide on <code><a href="https://blog.finxter.com/np-linspace/" data-type="post" data-id="4876" target="_blank" rel="noreferrer noopener">linspace()</a></code> with video if you need some background there.</p>



<p>Let&#8217;s dive into the steps in the code to get this plot done next. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Step 1: Import Libraries</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
</pre>



<p>Here we are importing the necessary libraries. Numpy is for numerical operations, Matplotlib&#8217;s <code>pyplot</code> is for plotting, and <code>cm</code> from Matplotlib is for working with colormaps.</p>



<h2 class="wp-block-heading">Step 2: Generate Data</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = np.linspace(-5, 5, 101)
y = np.linspace(-5, 5, 101)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
</pre>



<p>Here, <code>linspace</code> generates 101 evenly spaced points between -5 and 5 for both x and y. </p>



<p>You can watch our explainer video on the function here: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Use np.linspace() in Python? A Helpful Illustrated Guide" width="937" height="527" src="https://www.youtube.com/embed/vPZwZfd-aNY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/np-linspace/" data-type="URL" data-id="https://blog.finxter.com/np-linspace/" target="_blank" rel="noreferrer noopener">How to Use <code>np.linspace()</code> in Python? A Helpful Illustrated Guide</a></p>



<p>The NumPy function <code>meshgrid</code> takes two 1D arrays representing the Cartesian coordinates in the x and y axis and produces two 2D arrays. </p>



<p>The Z array is a 2D array that represents our &#8220;heights&#8221; and is calculated by applying the sine function to the square root of the sum of the squares of X and Y, essentially creating a 2D sine wave.</p>



<h2 class="wp-block-heading">Step 3: Prepare the Figure</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
</pre>



<p>We first create a figure object, and then add a subplot to it. The <code>'111'</code> argument means that we want to create a grid with 1 row and 1 column and place the subplot in the first (and only) cell of this grid. The <code>projection='3d'</code> argument means that we want this subplot to be a 3D plot.</p>



<p>Do you need a quick refresher on subplots? Check out our video on the Finxter blog: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Matplotlib Subplot - A Helpful Illustrated Guide" width="937" height="703" src="https://www.youtube.com/embed/gNy6D6JaePI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/matplotlib-subplot/" data-type="URL" data-id="https://blog.finxter.com/matplotlib-subplot/" target="_blank" rel="noreferrer noopener">Matplotlib Subplot – A Helpful Illustrated Guide</a></p>



<h2 class="wp-block-heading">Step 4: Prepare Colormap</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cmap = cm.viridis
norm = plt.Normalize(Z.min(), Z.max())
</pre>



<p>Here we&#8217;re choosing a colormap (<code>cm.viridis</code>), and then creating a normalization object (<code>plt.Normalize</code>) using the minimum and maximum values of Z. This normalization object will later be used to map the heights in Z to colors in the colormap.</p>



<h2 class="wp-block-heading">Step 5: Plot the Surface</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=cmap(norm(Z)), alpha=0.9, linewidth=0)
</pre>



<p>The method <code>ax.plot_surface()</code> plots the 3D surface. </p>



<ul class="wp-block-list">
<li>The arguments <code>X, Y, Z</code> are the coordinates for the plot. </li>



<li>The <code>rstride</code> and <code>cstride</code> parameters determine the stride (step size) for row and column data respectively, </li>



<li><code>facecolors</code> parameter takes the colormap applied on the normalized Z, </li>



<li><code>alpha</code> is used for blending value, between 0 (transparent) and 1 (opaque), and </li>



<li><code>linewidth</code> determines the line width of the surface plot.</li>
</ul>



<h2 class="wp-block-heading">Step 6: Add a Color Bar</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">m = cm.ScalarMappable(cmap=cmap, norm=norm)
m.set_array(Z)
fig.colorbar(m)
</pre>



<p>A <code>ScalarMappable</code> object is created with the same colormap and normalization as our surface plot. Then we associate this object with our Z array using the <code>set_array</code> function. Finally, we add a color bar to the figure that represents how the colors correspond to the Z values.</p>



<h2 class="wp-block-heading">Step 7: Set Labels and Show the Plot</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
</pre>



<p>Here, we&#8217;re setting the labels for each axis (X, Y, Z). Finally, <code>plt.show()</code> is called to display the plot. The plot will remain visible until all figures are closed.</p>



<p>Instead of using the <code>plot.show()</code> function to see the output, you can use the <code>plt.savefig('output.jpeg')</code> statement to save it in a file <code>'output.jpeg'</code>.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/matplotlib-full-guide/" data-type="URL" data-id="https://blog.finxter.com/matplotlib-full-guide/" target="_blank" rel="noreferrer noopener">Matplotlib — A Simple Guide with Videos</a></p>



<p></p>
<p>The post <a href="https://blog.finxter.com/how-do-i-make-a-3d-waterfall-plot-with-colored-heights-in-python/">How Do I Make a 3D Waterfall Plot with Colored Heights in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python 🐍 Put Legend Outside Plot 📈 &#8211; Easy Guide</title>
		<link>https://blog.finxter.com/python-%f0%9f%90%8d-put-legend-outside-plot-%f0%9f%93%88-easy-guide/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 22 Apr 2023 18:55:40 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Seaborn]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1311124</guid>

					<description><![CDATA[<p>Are you tired of feeling boxed in by your Python plots and ready to break free from the constraints of traditional legend placement? In this guide, I&#8217;ll show you how to put legends outside your plot for (click to 🦘 jump): Let&#8217;s start with the first! 👇👩‍💻 Matplotlib Put Legend Outside Plot Let&#8217;s start with ... <a title="Python 🐍 Put Legend Outside Plot 📈 &#8211; Easy Guide" class="read-more" href="https://blog.finxter.com/python-%f0%9f%90%8d-put-legend-outside-plot-%f0%9f%93%88-easy-guide/" aria-label="Read more about Python 🐍 Put Legend Outside Plot 📈 &#8211; Easy Guide">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-%f0%9f%90%8d-put-legend-outside-plot-%f0%9f%93%88-easy-guide/">Python 🐍 Put Legend Outside Plot 📈 &#8211; Easy Guide</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Are you tired of feeling boxed in by your Python plots and ready to break free from the constraints of traditional legend placement?</p>



<p>In this guide, I&#8217;ll show you how to put legends outside your plot for (click to <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f998.png" alt="🦘" class="wp-smiley" style="height: 1em; max-height: 1em;" /> jump): </p>



<ul class="wp-block-list">
<li><a href="#matplotlib" data-type="internal" data-id="#matplotlib" target="_blank" rel="noreferrer noopener">Matplotlib</a></li>



<li><a href="#seaborn" data-type="internal" data-id="#seaborn">Seaborn</a></li>



<li><a href="#pandas" data-type="internal" data-id="#pandas">Pandas</a></li>



<li><a href="#bokeh">Bokeh</a></li>
</ul>



<p>Let&#8217;s start with the first! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f4bb.png" alt="👩‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading" id="matplotlib">Matplotlib Put Legend Outside Plot</h2>



<p>Let&#8217;s start with various ways to position the legend outside for better visualization and presentation.</p>



<h3 class="wp-block-heading">Matplotlib Set Legend Outside Plot (General)</h3>



<p class="has-global-color-8-background-color has-background">First, let&#8217;s adjust the legend&#8217;s position outside the plot in general. To do this, use the <code>bbox_to_anchor</code> parameter in the legend function like this: <code>matplotlib.pyplot.legend(bbox_to_anchor=(x, y))</code> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f603.png" alt="😃" class="wp-smiley" style="height: 1em; max-height: 1em;" />. Here, adjust the values of <code>x</code> and <code>y</code> to control the legend&#8217;s position.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="791" height="520" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-220.png" alt="" class="wp-image-1311674" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-220.png 791w, https://blog.finxter.com/wp-content/uploads/2023/04/image-220-300x197.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-220-768x505.png 768w" sizes="auto, (max-width: 791px) 100vw, 791px" /></figure>
</div>


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="13" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

# Sample data for plotting
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125]

# Create the plot
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')

# Set the legend's position outside the plot using bbox_to_anchor
plt.legend(bbox_to_anchor=(1.05, 1))

# Add axis labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plotting with External Legend')

# Display the plot
plt.show()
</pre>



<p>In this example, the <code>bbox_to_anchor</code> parameter is set to <code>(1.05, 1)</code>, which moves the legend slightly to the right of the plot.</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: The <code>bbox_to_anchor</code> parameter in <code>matplotlib.pyplot.legend()</code> uses a tuple of two values, <code>x</code> and <code>y</code>, to control the position of the legend. <code>x=0/1</code> controls the <strong><em>left/right</em></strong> and <code>y=0/1</code> controls the <strong><em>bottom/top</em></strong> legend placement.</p>



<p>Generally, in axes coordinates:</p>



<ul class="wp-block-list">
<li><code>(0, 0)</code> represents the <strong>left-bottom</strong> corner of the axes.</li>



<li><code>(0, 1)</code> represents the <strong>left-top</strong> corner of the axes.</li>



<li><code>(1, 0)</code> represents the <strong>right-bottom</strong> corner of the axes.</li>



<li><code>(1, 1)</code> represents the <strong>right-top</strong> corner of the axes.</li>
</ul>



<p>However, the values of <code>x</code> and <code>y</code> are not limited to the range <code>[0, 1]</code>. You can use values outside of this range to place the legend beyond the axes&#8217; boundaries.</p>



<p>For example:</p>



<ul class="wp-block-list">
<li>(1.05, 1) places the legend slightly to the right of the top-right corner of the axes.</li>



<li>(0, 1.1) places the legend slightly above the top-left corner of the axes.</li>
</ul>



<p>Using negative values is also allowed. For example:</p>



<ul class="wp-block-list">
<li>(-0.3, 0) places the legend to the left of the bottom-left corner of the axes.</li>



<li>(1, -0.2) places the legend below the bottom-right corner of the axes.</li>
</ul>



<p>The range of <code>x</code> and <code>y</code> depends on the desired position of the legend relative to the plot. By adjusting these values, you can fine-tune the legend&#8217;s position to create the perfect visualization. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ab.png" alt="💫" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<h3 class="wp-block-heading">Matplotlib Set Legend Below or Above Plot</h3>



<p class="has-global-color-8-background-color has-background">To place the legend below the plot, you can set the <code>loc</code> parameter as &#8216;upper center&#8217; and use <code>bbox_to_anchor</code> like this: <code>plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1))</code>. For placing the legend above the plot, use <code>bbox_to_anchor=(0.5, 1.1)</code> instead <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ca.png" alt="📊" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="929" height="436" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-221.png" alt="" class="wp-image-1311717" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-221.png 929w, https://blog.finxter.com/wp-content/uploads/2023/04/image-221-300x141.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-221-768x360.png 768w" sizes="auto, (max-width: 929px) 100vw, 929px" /></figure>
</div>


<h3 class="wp-block-heading">Matplotlib Set Legend Left of Plot (Upper, Center, Lower Left)</h3>



<p>For positioning the legend to the left of the plot, use the following examples:</p>



<ul class="wp-block-list">
<li>Upper left: <code>plt.legend(loc='center left', bbox_to_anchor=(-0.2, 0.5))</code> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f31f.png" alt="🌟" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>



<li>Center left: <code>plt.legend(loc='center left', bbox_to_anchor=(-0.1, 0.5))</code></li>



<li>Lower left: <code>plt.legend(loc='lower left', bbox_to_anchor=(-0.2, 0))</code></li>
</ul>



<h3 class="wp-block-heading">Matplotlib Set Legend Right of Plot (Upper, Center, Lower Right)</h3>



<p>To position the legend to the right of the plot, you can try the following:</p>



<ul class="wp-block-list">
<li>Upper right: <code>plt.legend(loc='upper right', bbox_to_anchor=(1.1, 1))</code> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f44d.png" alt="👍" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>



<li>Center right: <code>plt.legend(loc='center right', bbox_to_anchor=(1.1, 0.5))</code></li>



<li>Lower right: <code>plt.legend(loc='lower right', bbox_to_anchor=(1.1, 0))</code></li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="447" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-222-1024x447.png" alt="" class="wp-image-1311719" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-222-1024x447.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-222-300x131.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-222-768x335.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-222.png 1073w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">Matplotlib Set Subplots Legend Outside Plot</h3>



<p class="has-global-color-8-background-color has-background">When working with subplots, you can place a single, unified legend outside the plot by iterating over the axes and using the <code>legend()</code> method on the last axis <a href="https://stackoverflow.com/questions/4700614/how-to-put-the-legend-outside-the-plot">(source)</a> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f60a.png" alt="😊" class="wp-smiley" style="height: 1em; max-height: 1em;" />. Remember to use the <code>bbox_to_anchor</code> parameter to control the legend&#8217;s position.</p>



<p>Here&#8217;s an example that does two things, i.e., (1) placing the legend on the right and (2) adjusting the layout to accommodate the external legend:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="662" height="460" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-223.png" alt="" class="wp-image-1311729" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-223.png 662w, https://blog.finxter.com/wp-content/uploads/2023/04/image-223-300x208.png 300w" sizes="auto, (max-width: 662px) 100vw, 662px" /></figure>
</div>


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="35" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt

# Sample data for plotting
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create subplots
fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True)

# Plot data on the first subplot
axes[0].plot(x, y1, label='sin(x)')
axes[0].set_title('Sine Wave')

# Plot data on the second subplot
axes[1].plot(x, y2, label='cos(x)', color='orange')
axes[1].set_title('Cosine Wave')

# Set a common x-label for both subplots
fig.text(0.5, 0.04, 'x', ha='center')

# Set y-labels for individual subplots
axes[0].set_ylabel('sin(x)')
axes[1].set_ylabel('cos(x)')

# Create a unified legend for both subplots
handles, labels = axes[-1].get_legend_handles_labels()
for ax in axes[:-1]:
    h, l = ax.get_legend_handles_labels()
    handles += h
    labels += l

# Place the unified legend outside the plot using bbox_to_anchor
fig.legend(handles, labels, loc='upper right', bbox_to_anchor=(1, 0.75))

# Adjust the layout to accommodate the external legend
fig.subplots_adjust(right=0.7)

# Display the subplots
plt.show()
</pre>



<h3 class="wp-block-heading">Legend Outside Plot Is Cut Off</h3>



<p>If your legend is cut off, you can adjust the saved figure&#8217;s dimensions using <code>plt.savefig('filename.ext', bbox_inches='tight')</code>. The <code>bbox_inches</code> parameter with the value &#8216;tight&#8217; will ensure that the whole legend is visible on the saved figure <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f389.png" alt="🎉" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>



<h3 class="wp-block-heading">Add Legend Outside a Scatter Plot</h3>



<p>For a scatter plot, you can use the same approach as mentioned earlier by adding the <code>loc</code> and <code>bbox_to_anchor</code> parameters to position the legend outside the plot. For instance, <code>plt.legend(loc='upper right', bbox_to_anchor=(1.1, 1))</code> will place the legend in the upper right corner outside the scatter plot <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>



<p>If your legend is cut off when placing it outside the plot in Python&#8217;s Matplotlib, you can adjust the layout and save or display the entire figure, including the external legend, by following these steps:</p>



<ol class="wp-block-list">
<li>Use the <code>bbox_to_anchor</code> parameter in the <code>legend()</code> function to control the position of the legend.</li>



<li>Adjust the layout of the figure using the <code>subplots_adjust()</code> or <code>tight_layout()</code> function to make room for the legend.</li>



<li>Save or display the entire figure, including the external legend.</li>
</ol>



<p>Here&#8217;s an example demonstrating these steps:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="462" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-224-1024x462.png" alt="" class="wp-image-1311730" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-224-1024x462.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-224-300x135.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-224-768x346.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-224.png 1113w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

# Sample data for plotting
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125]

# Create the plot
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')

# Set the legend's position outside the plot using bbox_to_anchor
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')

# Add axis labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plotting with External Legend')

# Adjust the layout to accommodate the external legend
plt.subplots_adjust(right=0.7)

# Display the plot
plt.show()
</pre>



<p>In this example, you use the <code>subplots_adjust()</code> function to adjust the layout of the figure and make room for the legend. </p>



<p>You can also use the <code>tight_layout()</code> function, which automatically adjusts the layout based on the elements in the figure:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="508" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-225-1024x508.png" alt="" class="wp-image-1311731" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-225-1024x508.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-225-300x149.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-225-768x381.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-225.png 1195w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># ...
# Set the legend's position outside the plot using bbox_to_anchor
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')

# Add axis labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plotting with External Legend')

# Automatically adjust the layout to accommodate the external legend
plt.tight_layout(rect=[0, 0, 0.7, 1])

# Display the plot
plt.show()
</pre>



<p>In this case, the <code>rect</code> parameter is a list <code>[left, bottom, right, top]</code>, which specifies the normalized figure coordinates of the new bounding box for the subplots. Adjust the values in the <code>rect</code> parameter as needed to ensure the legend is not cut off.</p>



<h2 class="wp-block-heading">Additional Legend Configurations</h2>



<p>In this section, you&#8217;ll learn about some additional ways to customize the legend for your plots in Python using Matplotlib. This will help you create more meaningful and visually appealing visualizations. However, feel free to skip ahead to the following sections on plotting the legend outside the figure in Seaborn, Pandas, and Bokeh.</p>



<h3 class="wp-block-heading">Python Set Legend Position</h3>



<p>As you already know by now, you can place the legend at a specific position in the plot by using the <code>bbox_to_anchor</code> parameter. For example, you could place the legend outside the plot to the right by passing <code>(1.05, 0.5)</code> as the argument:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
plt.legend(bbox_to_anchor=(1.05, 0.5))</pre>



<p>This will place the legend slightly outside the right border of the plot, with its vertical center aligned with the plot center.</p>



<h3 class="wp-block-heading">Python Set Legend Location</h3>



<p>You can easily change the location of the legend by using the <code>loc</code> parameter. Matplotlib allows you to use predefined locations like <code>'upper right'</code>, <code>'lower left'</code>, etc., or use a specific coordinate by passing a tuple:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.legend(loc='upper left')</pre>



<p>This will place the legend in the upper-left corner of the plot.<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4cd.png" alt="📍" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h3 class="wp-block-heading">Python Set Legend Font Size</h3>



<p>To change the font size of the legend, you can use the <code>fontsize</code> parameter. You can pass a numeric value or a string like <code>'small'</code>, <code>'medium'</code>, or <code>'large'</code> to set the font size:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.legend(fontsize='large')</pre>



<p>This will increase the font size of the legend text.<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f603.png" alt="😃" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h3 class="wp-block-heading">Python Set Legend Title</h3>



<p>If you want to add a title to your legend, you can use the <code>title</code> parameter. Just pass a string as the argument to set the title:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.legend(title='My Legend Title')</pre>



<p>This will add the title &#8220;My Legend Title&#8221; above your legend.<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f44d.png" alt="👍" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h3 class="wp-block-heading">Python Set Legend Labels</h3>



<p>If you&#8217;d like to customize the legend labels, you can pass the <code>labels</code> parameter. It takes a list of strings as the argument:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.legend(labels=['Label 1', 'Label 2'])</pre>



<p>Your legend will now display the custom labels &#8220;Label 1&#8221; and &#8220;Label 2&#8221; for the corresponding plot elements.<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3f7.png" alt="🏷" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h3 class="wp-block-heading">Python Set Legend Color</h3>



<p>Changing the color of the legend text and lines can be achieved by using the <code>labelcolor</code> parameter. Just pass a color string or a list of colors:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.legend(labelcolor='red')</pre>



<p>This will change the color of the legend text and lines to red.<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f534.png" alt="🔴" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading" id="seaborn">Seaborn Put Legend Outside Plot</h2>



<p>In this section, I&#8217;ll show you how to move the legend outside the plot using Seaborn. Let&#8217;s dive into various ways of setting the legend position, like below, above, left or right of the plot.<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f468-200d-1f4bb.png" alt="👨‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h3 class="wp-block-heading">Sns Set Legend Outside Plot (General)</h3>



<p>First, let&#8217;s talk about the general approach:</p>



<p class="has-global-color-8-background-color has-background">You can use the <code>legend()</code> function and the <code>bbox_to_anchor</code> parameter from Matplotlib to move the legend. You can combine this with the <code>loc</code> parameter to fine-tune the legend&#8217;s position.<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4c8.png" alt="📈" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>Here&#8217;s a quick example:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="669" height="455" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-226.png" alt="" class="wp-image-1311735" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-226.png 669w, https://blog.finxter.com/wp-content/uploads/2023/04/image-226-300x204.png 300w" sizes="auto, (max-width: 669px) 100vw, 669px" /></figure>
</div>


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="12" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import seaborn as sns
import matplotlib.pyplot as plt

# Sample data for plotting
tips = sns.load_dataset("tips")

# Create a Seaborn plot with axis variable 'ax'
fig, ax = plt.subplots()
sns_plot = sns.scatterplot(x="total_bill", y="tip", hue="day", data=tips, ax=ax)

# Set the legend's position outside the plot using bbox_to_anchor on 'ax'
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)

# Add axis labels and title
ax.set_xlabel('Total Bill')
ax.set_ylabel('Tip')
ax.set_title('Tips by Total Bill and Day')

# Display the plot
plt.show()
</pre>



<h3 class="wp-block-heading">Sns Set Legend Below or Above Plot</h3>



<p>Now let&#8217;s move the legend below or above the plot.<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Simply adjust the <code>bbox_to_anchor</code> parameter accordingly. For example, to place the legend below the plot, you can use <code>bbox_to_anchor=(0.5, -0.1)</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1))
</pre>



<p>And to place the legend above the plot, use <code>bbox_to_anchor=(0.5, 1.1)</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='lower center', bbox_to_anchor=(0.5, 1.1))
</pre>



<h3 class="wp-block-heading">Sns Set Legend Left of Plot (Upper, Center, Lower Left)</h3>



<p>Similarly, to position the legend on the left side of the plot, you can use the following code snippets:<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3a8.png" alt="🎨" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>Upper left:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='upper right', bbox_to_anchor=(-0.15, 1))
</pre>



<p>Center left:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='center right', bbox_to_anchor=(-0.15, 0.5))
</pre>



<p>Lower left:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='lower right', bbox_to_anchor=(-0.15, 0))
</pre>



<h3 class="wp-block-heading">Sns Set Legend Right of Plot (Upper, Center, Lower Right)</h3>



<p>Lastly, to place the legend on the right side of the plot, adjust the <code>bbox_to_anchor</code> parameter like so:<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>Upper right:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='upper left', bbox_to_anchor=(1.05, 1))
</pre>



<p>Center right:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='center left', bbox_to_anchor=(1.05, 0.5))
</pre>



<p>Lower right:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='lower left', bbox_to_anchor=(1.05, 0))
</pre>



<p>With these techniques, you can easily position the legend outside the plot using Seaborn! Happy plotting!<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f52c.png" alt="👩‍🔬" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading" id="pandas">Pandas Put Legend Outside Plot</h2>



<p class="has-global-color-8-background-color has-background">When working with Pandas and Matplotlib, you often want to move the legend outside the plot <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f5bc.png" alt="🖼" class="wp-smiley" style="height: 1em; max-height: 1em;" /> to improve readability. No worries! You can do this by taking advantage of the fact that <code>.plot()</code> returns a Matplotlib axis, enabling you to add <code>.legend(bbox_to_anchor=(x, y))</code> to your code. </p>



<p>Here&#8217;s how:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="988" height="478" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-227.png" alt="" class="wp-image-1311740" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-227.png 988w, https://blog.finxter.com/wp-content/uploads/2023/04/image-227-300x145.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-227-768x372.png 768w" sizes="auto, (max-width: 988px) 100vw, 988px" /></figure>
</div>


<p>First, import the necessary libraries like Pandas and Matplotlib:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
import matplotlib.pyplot as plt
</pre>



<p>Create your DataFrame and plot it using the <code>plot()</code> function, like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
ax = df.plot()
</pre>



<p>Next, you&#8217;ll want to place the legend outside the plot. Adjust the coordinates parameter, <code>bbox_to_anchor</code>, to position it according to your preferences. For example, if you want to place the legend to the right of the plot, use:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(bbox_to_anchor=(1.05, 1))

plt.tight_layout()
plt.show()
</pre>



<p>This code will place the legend to the right of the plot, at the top <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>



<h2 class="wp-block-heading" id="bokeh">Bokeh Put Legend Outside Plot</h2>



<p class="has-global-color-8-background-color has-background">Placing a legend outside the plot in Bokeh can be easily done by using the <code>add_layout</code> method. You&#8217;ll need to create a <code>Legend</code> object manually and then add it to your plot using <code>add_layout</code>. This gives you the flexibility to position the legend anywhere on your plot, which is particularly helpful when you have many curves that might be obscured by an overlapping legend. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f60a.png" alt="😊" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>Here&#8217;s a short example to help you move the legend outside the plot in Bokeh:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="722" height="718" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-228.png" alt="" class="wp-image-1311741" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-228.png 722w, https://blog.finxter.com/wp-content/uploads/2023/04/image-228-300x298.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-228-150x150.png 150w" sizes="auto, (max-width: 722px) 100vw, 722px" /></figure>
</div>


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from bokeh.plotting import figure, show
from bokeh.models import Legend, LegendItem
from bokeh.io import output_notebook
output_notebook()

# Example data
x = list(range(10))
y1 = [i**2 for i in x]
y2 = [i**0.5 for i in x]

# Create a figure
p = figure(title="Example Plot")

# Add line glyphs and store their renderer
r1 = p.line(x, y1, line_color="blue", legend_label="Line 1")
r2 = p.line(x, y2, line_color="red",  legend_label="Line 2")

# Create Legend object
legend = Legend(items=[
    LegendItem(label="Line 1", renderers=[r1]),
    LegendItem(label="Line 2", renderers=[r2])
], location="top_left")

# Add legend to plot
p.add_layout(legend, 'right')

# Show plot
show(p)
</pre>



<p>To ensure your plot is as clear as possible, we recommend experimenting with different legend positions and layouts. By customizing your plot, you can maintain a clean and organized display of your curves even when there&#8217;s a lot of information to convey. </p>



<p>With Bokeh, you have full control over your plot&#8217;s appearance, so enjoy exploring different options to find the perfect fit for your data! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4c8.png" alt="📈" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f389.png" alt="🎉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Keep Learning With Your Python Cheat Sheet! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>



<p>Feel free to download our free cheat sheet and join our tech and coding academy by downloading the free Finxter cheat sheets &#8212; it&#8217;s fun!</p>



<p>The post <a href="https://blog.finxter.com/python-%f0%9f%90%8d-put-legend-outside-plot-%f0%9f%93%88-easy-guide/">Python 🐍 Put Legend Outside Plot 📈 &#8211; Easy Guide</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Strategic Investing with Python: Ensuring Your Kids Have $70k at 21</title>
		<link>https://blog.finxter.com/project-using-python-to-plan-how-much-i-should-invest-for-my-kids-so-they-have-70k-at-age-21/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Fri, 06 Jan 2023 09:31:50 +0000</pubDate>
				<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Investment]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1039597</guid>

					<description><![CDATA[<p>As a parent, planning for your children&#8217;s future is one of the most important things you can do. To ensure they have the best possible start in life, I&#8217;ve been looking into ways to invest money to provide them with a lump sum of $70k when they reach 21. But I don&#8217;t want to spend ... <a title="Strategic Investing with Python: Ensuring Your Kids Have $70k at 21" class="read-more" href="https://blog.finxter.com/project-using-python-to-plan-how-much-i-should-invest-for-my-kids-so-they-have-70k-at-age-21/" aria-label="Read more about Strategic Investing with Python: Ensuring Your Kids Have $70k at 21">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/project-using-python-to-plan-how-much-i-should-invest-for-my-kids-so-they-have-70k-at-age-21/">Strategic Investing with Python: Ensuring Your Kids Have $70k at 21</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>As a parent, planning for your children&#8217;s future is one of the most important things you can do. </p>



<p>To ensure they have the best possible start in life, I&#8217;ve been looking into ways to invest money to provide them with a lump sum of $70k when they reach 21. But I don&#8217;t want to spend that much money at once when they turn 21.</p>



<p><strong><em>So what to do?</em></strong></p>



<p>In this blog post, I&#8217;ll be exploring how Python helped me figure out a simple investment plan, so I can give my kids a nice nest egg without needing to spend a lot of our (parents&#8217;) money at once.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Result</strong>: I need to set up a savings plan contributing $90 per month for 21 years in a vehicle earning 9% per year (e.g., S&amp;P500 ETF), so my kids get a $70k nest egg when they start into their own lives.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="956" height="637" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-26.png" alt="" class="wp-image-1039620" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-26.png 956w, https://blog.finxter.com/wp-content/uploads/2023/01/image-26-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-26-768x512.png 768w" sizes="auto, (max-width: 956px) 100vw, 956px" /></figure>
</div>


<p>Here&#8217;s the Python code &#8212; I&#8217;ll explain it in a moment:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5-8" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import numpy as np

# Define initial investment value, investment return, and monthly contributions
initial_investment = 1000
investment_return = 0.09
monthly_contributions = [30,60,90]
num_years = 21

# Create list of portfolio values over time for each savings rate
portfolio_values = []
for contribution in monthly_contributions:
    portfolio = [initial_investment]
    portfolio_value = initial_investment
    for i in range(1,num_years-1):
        portfolio_value = portfolio_value * (1 + investment_return) + contribution * 12
        portfolio.append(portfolio_value)
    portfolio_values.append(portfolio)

# Plot portfolio values over time
time = np.arange(1,num_years)
for i in range(len(monthly_contributions)):
    plt.plot(time, portfolio_values[i], label='$' + str(monthly_contributions[i]) + '/m')
plt.title('Portfolio Value over Time')
plt.xlabel('Time (years)')
plt.ylabel('Portfolio Value ($)')

# Add end value labels
for i in range(len(monthly_contributions)):
    plt.text(num_years-3, portfolio_values[i][-1], '$' + str(int(portfolio_values[i][-1]*1.3)))

plt.legend()
plt.show()
</pre>



<p>Result:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="796" height="687" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-25.png" alt="" class="wp-image-1039601" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-25.png 796w, https://blog.finxter.com/wp-content/uploads/2023/01/image-25-300x259.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-25-768x663.png 768w" sizes="auto, (max-width: 796px) 100vw, 796px" /></figure>
</div>


<p>This code snippet plots the value of a portfolio for different monthly contributions over a period of 21 years. </p>



<p>You specify the </p>



<ul class="wp-block-list">
<li>initial investment value, </li>



<li>investment return, </li>



<li>number of years, and </li>



<li>monthly contributions. </li>
</ul>



<p>Then, you <a href="https://blog.finxter.com/how-to-create-a-python-list/" data-type="post" data-id="10436" target="_blank" rel="noreferrer noopener">create a list</a> to store the portfolio values over time for each monthly contribution.</p>



<p>You calculate the portfolio values by multiplying the previous value of the portfolio by the investment return plus the contribution for each month. You repeat this calculation over the number of years minus one, taking the initial investment into account.</p>



<p>You use Matplotlib to plot the portfolio values. The x-axis is the time in years and the y-axis is the portfolio value in dollars. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/matplotlib-full-guide/" data-type="post" data-id="20151" target="_blank" rel="noreferrer noopener">A Video Guide on Matplotlib</a></p>



<p>You add a title and labels to the plot. You also add the end value for each of the portfolios to the plot with a text label. Finally, you display the plot.</p>



<h2 class="wp-block-heading">Action Steps</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="957" height="637" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-27.png" alt="" class="wp-image-1039634" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-27.png 957w, https://blog.finxter.com/wp-content/uploads/2023/01/image-27-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-27-768x511.png 768w" sizes="auto, (max-width: 957px) 100vw, 957px" /></figure>
</div>


<ul class="wp-block-list">
<li>Copy the code into your own Python script.</li>



<li>Figure out your (base) investment goals for your kids or yourself. What do you need to accomplish? What would be your dream outcome?</li>



<li>Change the input values until you&#8217;re happy with your results.</li>
</ul>



<p>You can check out our <a rel="noreferrer noopener" href="https://academy.finxter.com/university/matplotlib-a-guide-to-becoming-a-data-visualization-wizard/" data-type="URL" data-id="https://academy.finxter.com/university/matplotlib-a-guide-to-becoming-a-data-visualization-wizard/" target="_blank">Finxter Academy course on Matplotlib</a> to learn all you need to use plotting and data visualization in Python.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>This is part of our <strong>100 practical Python projects</strong> series. <a rel="noreferrer noopener" href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank">Subscribe here</a>.</p>






<p>By the way, Finxter <strong>Mark</strong> came up with this clever script that is kind of a generalization of the previous code snippet. Very nicely done!</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># A program from the 100 Projects for 2023 Series at Finxter.com
# 6 January 2023

import matplotlib.pyplot as plt
import numpy as np

'''Get the initial values from the user
for the plots.  Initial investment, return rate, contributions (number of them for plot)
'''
# Define initial investment value, investment return, and monthly contributions

initial_investment = int(input('Initial Invest: '))
investment_return = float(input('Return Rate (ex 0.03): '))

# creating an empty list
monthly_contributions = []

# number of elements as input
n = int(input("Enter number of different monthly contribution amounts: "))

# iterating till the range
for i in range(0, n):
    # grab the elements and append, let user know which one we are on of the set
    ele = int(input('Contribution amount ' + str(i+1) + ': '))
    monthly_contributions.append(ele)  # adding the element

num_years = int(input('Years: '))



# Create list of portfolio values over time for each savings rate
portfolio_values = []
for contribution in monthly_contributions:
    portfolio = [initial_investment]
    portfolio_value = initial_investment
    for i in range(1,num_years-1):
        portfolio_value = portfolio_value * (1 + investment_return) + contribution * 12
        portfolio.append(portfolio_value)
    portfolio_values.append(portfolio)

# Plot portfolio values over time
time = np.arange(1,num_years)
for i in range(len(monthly_contributions)):
    plt.plot(time, portfolio_values[i], label='$' + str(monthly_contributions[i]) + '/m')
plt.title('Portfolio Value over Time')
plt.xlabel('Time (years)')
plt.ylabel('Portfolio Value ($)')

# Add end value labels
for i in range(len(monthly_contributions)):
    plt.text(num_years-2, portfolio_values[i][-1], '$' + str(int(portfolio_values[i][-1]*1.3)))

plt.legend()
plt.show()
</pre>



<p>Here&#8217;s an example run of the flexible scripts with three kids investing $1000 in a lump sum (each) and $50, $100, and $200 monthly contributions for 20 years:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="833" height="581" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-115.png" alt="" class="wp-image-1055074" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-115.png 833w, https://blog.finxter.com/wp-content/uploads/2023/01/image-115-300x209.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-115-768x536.png 768w" sizes="auto, (max-width: 833px) 100vw, 833px" /></figure>
</div><p>The post <a href="https://blog.finxter.com/project-using-python-to-plan-how-much-i-should-invest-for-my-kids-so-they-have-70k-at-age-21/">Strategic Investing with Python: Ensuring Your Kids Have $70k at 21</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-04-20 04:59:27 by W3 Total Cache
-->