<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anna Gordun Peiro on Medium]]></title>
        <description><![CDATA[Stories by Anna Gordun Peiro on Medium]]></description>
        <link>https://medium.com/@gordunanna?source=rss-6b453743a21c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xcymf5kJLwwvARr1elDC_g@2x.jpeg</url>
            <title>Stories by Anna Gordun Peiro on Medium</title>
            <link>https://medium.com/@gordunanna?source=rss-6b453743a21c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:56:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gordunanna/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Can You Tell Free Python Art from Multi-Million Dollar Pieces?]]></title>
            <link>https://medium.com/data-science/can-you-tell-free-python-art-from-multi-million-dollar-pieces-c292ec0747db?source=rss-6b453743a21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c292ec0747db</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[art]]></category>
            <dc:creator><![CDATA[Anna Gordun Peiro]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 13:02:11 GMT</pubDate>
            <atom:updated>2024-11-14T21:51:41.749Z</atom:updated>
            <content:encoded><![CDATA[<h4>Follow along for a Python generative art tutorial, inspired by Piet Mondrian and Josef Albers. From Code to Canvas, Part I.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCJHMOtnbJerV4Vvky83cQ.png" /><figcaption>Which are the three real pieces? Image created by Author from <a href="https://unsplash.com/es/@yoyoqua">Ioana Cristiana’s</a> photo. Piet Mondrian’s works are Public Domain. An artwork falls into the <strong>public domain 70 years</strong> after the death of the artist.</figcaption></figure><p>One of these pieces has been generated by Python and the rest are Piet Mondrian originals. Which one is the odd one out? I’ll give you the answer a few paragraphs down but first I need to tell you why I am using Python for art generation and not a fancy Gen-AI tool.</p><p>As a creative art enthusiast born with zero artistic skills, I saw the launch of DALL-E and others as the opportunity to cover my entire flat in “my” masterpieces without needing to master a brush.</p><p>That wasn&#39;t the case and my walls remain a blank canvas. I didn’t manage to create anything display-worthy, but most importantly — DALL-E killed the vibe.</p><p>Why?</p><p>Because most of the magic in art comes from feeling our way through the creative process. It’s a journey — not just an outcome. AI art felt too dictated, too random, and too cold for me.</p><p>So that got me thinking: is there a sweet middle spot? Is there a way to have random but controlled generative art and still get that dopamine/pride moment of a finished piece? And needless to say, without actual artistic skills?</p><p>In this article I will show you how I created two museum-worthy art pieces, and we will uncover which is the Mondrian impostor.</p><h3>How to create Piet Mondrian fakes</h3><p>For my first Generative Art piece, I’ve taken inspiration from Piet Mondrian, a pioneer of abstract art. His work is presented as an abstract arrangement of lines, colours and shapes.</p><p>Here is a little sample of some of his most iconic pieces:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3AVA0rFNAS02xhNgpnJug.jpeg" /><figcaption>Image created by Author. Piet Mondrian’s work is Public Domain.</figcaption></figure><blockquote>Do you know which one is the impostor already?</blockquote><p>If you’re interested in giving it a try, you just have to install the “<a href="https://pypi.org/project/mondrian-maker/#description">mondrian-maker</a>” Python package to paint new pieces like this:</p><blockquote>The mondrian-maker package was created by Andrew Bowen and is published under a GNU General Public License.</blockquote><pre>from mondrian_maker.mondrian import mondrian<br><br>m = mondrian()<br>m.make_mondrian()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*SNM9PQ6ujDlsEa_rk2JthQ.png" /><figcaption>Composition generated by Author</figcaption></figure><p>Part of the fun is that a new piece will be generated every time you call make_mondrian(). Not all of them will be “painting-worthy” so I generated 100 and chose my favourites.</p><pre>for i in range(0,100):<br>    f,ax=m.make_mondrian()<br>    f.savefig(f&quot;{i}_mondrian.png&quot;)</pre><p>And the answer to the Python or original game? The impostor is the <strong>third one from the left</strong>😉. The rest of the pieces are (from left to right): <em>Composition No. I with Red and Blue (1938)</em>; <em>Composition with Red, Yellow and Blue (1942)</em>;<em> Composition No.10 (1939)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LW-BL5CajCmsa6xUPjnnLg.png" /><figcaption>Puzzle solution!. Image generated by Author. Piet Mondrian’s work is Public Domain</figcaption></figure><blockquote>Did you guess right? Let me know in the comments!</blockquote><p>Keep reading if you want to know how to recreate another thousand-dollar art piece:</p><h3>Josef Albers — Homage to the Square</h3><p>While Mondrian’s work really caught my attention, I wanted to start from scratch and make something of my own. That’s why I turned to Josef Albers’ <em>Homage to the Square</em> series. I am drawn to the way he played with perspective and colour, plus there’s something about the “simple” look that felt like the right place to dive in. Judge by yourself:</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/archillect/status/1689116981402701824&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fdac2de1988e07f4011c6edec9d9222/href">https://medium.com/media/6fdac2de1988e07f4011c6edec9d9222/href</a></iframe><p>Now, before we start drawing squares, there are two key secrets for Python generative art that you should know:</p><ul><li><strong>Reproducibility: </strong>We want our art to be random but also to be able to generate the exact painting again. By using <em>numpy.random.seed()</em> we can make sure that random numbers remain the same across different runs.</li></ul><pre>import numpy as np<br><br>constant=12<br>np.random.seed(constant)<br><br># From now on all generated random numbers are reproducible if constant=12<br># To get different random numbers, choose a new constant</pre><ul><li><strong>Colour theory: </strong>Artists use<strong> </strong>combinations of colours to generate visually appealing colour palettes. The coding secret for this is to use <a href="https://github.com/BlakeRMills/MetBrewer"><em>MetBrewer</em></a>, a Python library that contains 56 beautiful palettes inspired by works at the Metropolitan Museum of Art in New York.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuCMFVdhilB1jNcqwTobUQ.png" /><figcaption>Screenshot from <a href="https://github.com/BlakeRMills/MetBrewer">MetBrewer</a> (Creative Commons License)</figcaption></figure><pre>from met_brewer import met_brew<br>palette=met_brew(name=&quot;Hokusai3&quot;, brew_type=&quot;discrete&quot;)</pre><p>🎨Now we are ready to start painting!🎨</p><blockquote>Spoiler alert: the next blocks of code reveal how to create an Homage to the Square lookalike painting, skip them if you prefer to try it yourself first.</blockquote><p>1- I first build a function that generates the following:</p><ul><li>The 4 edges of a square (x0,x1,y0,y1)</li><li>A random colour for each square</li></ul><pre>from numpy import random<br><br>def rectangle_generator(palette): <br>    rectangle=[]<br><br>    big={&#39;x0&#39;: 0, &#39;y0&#39;: 0, &#39;x1&#39;: 1, &#39;y1&#39;: 1,&#39;color&#39;:palette[random.randint(len(palette))]} <br>    rectangle.append(big)<br><br>    middle={&#39;x0&#39;: 0.1, &#39;y0&#39;: 0.05, &#39;x1&#39;: 0.9, &#39;y1&#39;: 0.85,&#39;color&#39;:palette[random.randint(len(palette))]}<br>    rectangle.append(middle)<br><br>    small={&#39;x0&#39;: 0.2, &#39;y0&#39;: 0.1, &#39;x1&#39;: 0.8, &#39;y1&#39;: 0.7,&#39;color&#39;:palette[random.randint(len(palette))]}<br>    rectangle.append(small)<br><br>    tiny={&#39;x0&#39;: 0.3, &#39;y0&#39;: 0.15, &#39;x1&#39;: 0.7, &#39;y1&#39;: 0.55,&#39;color&#39;:palette[random.randint(len(palette))]}<br>    rectangle.append(tiny)<br><br>    return rectangle</pre><p>2- I then plotted each square coordinate with Plotly</p><pre>import plotly.graph_objects as go<br>import plotly.express as px<br>import numpy as np<br>from met_brewer import met_brew<br>import plotly.io as pio<br><br>#For reproducibility<br>np.random.seed(73)<br><br>#Choose a beautiful palette from met_brewer<br>palette=met_brew(name=&quot;Morgenstern&quot;, n=30,brew_type=&quot;continuous&quot;)       <br><br># Generate rectangles with defined palette<br>rectangles=rectangle_generator(palette)<br><br># Plot!<br><br># Setting canvas<br><br>fig=go.Figure()<br><br>fig.update_layout(<br>    autosize=False,<br>    width=800,<br>    height=800,<br>    )<br><br>fig.update_xaxes(range=[0, 1], showgrid=False,visible=False)<br>fig.update_yaxes(range=[0, 1],visible=False)<br><br># Start painting<br><br>for rect in rectangles:<br>    fig.add_shape(<br>        type=&quot;rect&quot;,<br>        x0=rect[&#39;x0&#39;],y0=rect[&#39;y0&#39;],<br>        x1=rect[&#39;x1&#39;],y1=rect[&#39;y1&#39;],<br>        line=dict(color=rect[&#39;color&#39;],<br>                    width=2,),<br>        fillcolor=rect[&#39;color&#39;]<br>        )<br>    <br>fig.update_shapes(dict(xref=&#39;x&#39;, yref=&#39;y&#39;))<br>fig.show()<br>pio.write_image(fig, &quot;73morgensternplot.png&quot;, format=&quot;png&quot;, width=800, height=800, scale=3)</pre><p>And here’s the final result!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiF11axSsz7aqPpsUlGRAA.png" /><figcaption>I call this one: icream on a sunny day. Image by Author</figcaption></figure><p>Let me tell you why I truly enjoyed designing this art piece — and why I hope that you do too:</p><p>First, I had to crack the code on the square dimensions, making sure they matched the original piece’s perspective. Then came the fun (and slightly obsessive) part: playing with colour palettes waiting for that magical “aha” moment when everything just clicked.</p><p>I didn’t stop there. I generated over 100 paintings with different seed constants, basically becoming my own art curator and finding “the one”.</p><p>The best part? I got to skip hours of painting frustration only to end up with something “okayish.” And, I wasn’t let down by an overhyped Gen-AI tool. Instead, I let my imagination run and came out with a piece I’d proudly hang on my wall — or even buy.</p><p>In my opinion, art looks elevated and more expensive with a frame on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNfBJflFtLwILEg7eUJ75g.jpeg" /><figcaption>Framed painting, fyi I used levelframes.com to generate it. Picture by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIl4bxwmd3IvaB9pUw-eQg.jpeg" /><figcaption>Picture generated by Author</figcaption></figure><p>This is the first article of a new series: <strong>From Code to Canvas. </strong>I’m open to suggestions on Art pieces you’d like to code-recreate so feel free to leave a comment! And don’t forget to follow — your empty walls will thank you.</p><p><em>All images in this article are by the author except for Piet Mondrain’s works which are Public Domain.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c292ec0747db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/can-you-tell-free-python-art-from-multi-million-dollar-pieces-c292ec0747db">Can You Tell Free Python Art from Multi-Million Dollar Pieces?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Who Really Owns the Airbnbs You’re Booking? — Marketing Perception vs Data Analytics Reality]]></title>
            <link>https://medium.com/data-science/who-really-owns-the-airbnbs-youre-booking-marketing-perception-vs-data-analytics-reality-94407a32679c?source=rss-6b453743a21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/94407a32679c</guid>
            <category><![CDATA[airbnb]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <dc:creator><![CDATA[Anna Gordun Peiro]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 17:28:21 GMT</pubDate>
            <atom:updated>2024-10-03T17:28:21.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>Who Really Owns the Airbnbs You’re Booking? — Marketing Perception vs Data Analytics Reality</h3><h4>Over the last 20 years, Airbnb has spent billions on brand building as the authentic, novel and community-led alternative to hotels. But, are they really?</h4><p>In this article, I will use data from <a href="https://insideairbnb.com/">InsideAirbnb</a> to reveal Airbnb’s ownership patterns. Then, I’ll walk you through how I came to my conclusions so you can do the same for your city.</p><blockquote><a href="https://insideairbnb.com/"><strong>Inside Airbnb</strong></a><strong> </strong>is<strong> </strong>a mission driven project that provides data and advocacy about Airbnb’s impact on residential communities. All data is licensed under a <a href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>.</blockquote><p>I am sure you’ve seen the Airbnb ads featuring over-smiling hosts greeting guests in vibrant tourist-loving neighbourhoods. If you haven’t, check this one out:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnULyTg1ruU0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnULyTg1ruU0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnULyTg1ruU0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d70be1461eea0c8591d1b3bb324192e9/href">https://medium.com/media/d70be1461eea0c8591d1b3bb324192e9/href</a></iframe><p>I’ve personally been on Airbnb for over 5 years and even though I’ve stayed in very quirky and authentic places (my favourite has to be a Shepherd&#39;s Hut with a horse outside the door) I’ve recently realised that my recent experiences don’t live up to the expectations of Airbnb’s marketing.</p><p>Last week I stayed at an Airbnb for a weekend. I did a little treasure hunt involving unlocking many padlocks to find the keys. And I opened the door to a spotless flat which looked exactly like the pictures. But I was surprised to see no books or candles. It was completely empty, like no one had ever really lived there. The next day I didn’t meet any neighbours. I didn’t receive any restaurant recommendations from my host. And on the last day I left, leaving the keys inside, no one to wave me goodbye. I thought, have I just stayed in a hotel? Is this what Airbnb has turned into?</p><h3><strong>What Airbnb Wants You to Think</strong></h3><p>Airbnb’s focus on experiencing life as a local, or as they call it: “the feeling of truly belonging”, is reflected in many of their advertising campaigns:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FddRBr2It00k&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DddRBr2It00k&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FddRBr2It00k%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/64e4f76fc07a656ada9a9883c1c5265a/href">https://medium.com/media/64e4f76fc07a656ada9a9883c1c5265a/href</a></iframe><blockquote>Live there, because when you live in Paris, you have your own home</blockquote><p>This beautifully curated ad perfectly exemplifies Airbnb’s value proposition: live like a local and ditch that essenceless, standardised hotel reservation. Following a romantised local experience, Airbnb’s marketing paints an image of a trustful and wholehearted connection between hosts and guests.</p><p>It’s no surprise then, that a part of me felt deceived during my last trip. I had missed out on the entire Airbnb experience. That motivated me to research Airbnb’s listing data to answer my mind-racing questions:</p><ul><li>Has our Airbnb experience become standard and optimised for maximum profit?</li><li>Is the Airbnb community essence gone?</li></ul><h3><strong>The Reality</strong></h3><p>Multi-property ownership marks a turning point in whether we guests truly experience the “Airbnb Experience”.</p><p><strong>Why?</strong></p><p>Because, when booking accommodation from a “real estate investor” or host with a large portfolio of listings, we’ll likely be staying in a hotel-like business which has bought flats around the city to rent out. In that case, our host’s motivations will be primarily financial. Our stay will have been optimised for profit rather than the personal, local touch that Airbnb promised through its marketing. Essentially, the only real difference from a hotel stay will be access to a kitchen.</p><p>To analyse different levels of multi-property ownership, I classified hosts with 1–2 listings as likely individuals, while those with over 3 listings as professionals.</p><p>To make my point that the Airbnb experience might be just a perception, I accessed datasets from 15 cities in Europe and performed a Data Analysis to capture the prevalence of professional hosts vs individual hosts <em>(all details and code in the next section)</em>. Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uS9mw3iXzafufkmuj68fYA.png" /></figure><p>Each of the bars corresponds to a different city and the visualisation is split into two sides: left (<strong>green</strong> colours) for the % of listings owned by <strong>individuals</strong> and right ( <strong>bright</strong> colours) for the % of listings owned by <strong>professional</strong> hosts. The number of properties per host has been classified into 1, 2, +2, +5, +10 and +100. Some of the cities that I selected have strict lodging regulations in place that limit the maximum number of days a year that can be rented out <em>(Florence, London, Edinburgh, Rome, Paris, Copenhagen and Amsterdam).</em> Finally, the graph order is from highest to lowest professional ownership share.</p><p>What we can see from the graph:</p><ul><li>The majority of Airbnb’s in my analysis are owned by professionals.</li><li><strong>Barcelona</strong> has the highest share of professional ownership at 74%, compared to 26% for individuals.</li><li><strong>Amsterdam</strong> has the lowest share of professional ownership at just 5%, with 95% of listings owned by individuals, likely due to strict government regulations limiting rentals to a maximum of 30 days per year.</li><li>Cities with <strong>lax Airbnb Regulations</strong> allow for professional hosts to dominate the market.</li><li>Cities with <strong>strict Airbnb Regulations</strong> tend to push Airbnb professional hosts out of the picture.</li><li>There doesn’t seem to be a set limit on the maximum amount of listings per host.</li></ul><p>According to Airbnb, our experience with them is supposed to be authentic. However, by looking at the data, we’ve uncovered that <strong>3 out of 5 listings</strong> are hotel-like flats owned by rental <strong>investors</strong> (except when rentals are regulated). This disconnect between marketing perception and reality highlights, not only the influence of branding in our views, but the importance of initiatives such as InsideAirbnb.</p><p>I now know what to expect for my next stay — how about you? Will you get the full padlock treasure hunt experience? Dive into the coding if you’re curious!</p><h3><strong>How to Replicate My Study for Your City?</strong></h3><p>I’ve written a guide on how to perform this data analysis and generate the graph in the previous section. I am using the dataset from the city of Barcelona to illustrate the different data analysis steps.</p><p>After downloading the listings.csv.gz files from InsideAirbnb I opened them in Python without decompressing. I am using Polars for this project just to become familiar with the commands <em>(you can use Pandas if you wish)</em>:</p><pre>import polars as pl<br>df=pl.read_csv(&#39;listings.csv.gz&#39;)</pre><p>Here are the cities that I used for the analysis and the number of listings in each dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NazwQf4xNUTjq_jwIbHLWA.png" /><figcaption>Cities used for analysis. Image by author</figcaption></figure><p>If you like this packed bubble plot, make sure to check my last article:</p><p><a href="https://towardsdatascience.com/i-found-a-hidden-gem-in-matplotlibs-library-packed-bubble-charts-in-python-d0f5d892beb7">I found a hidden gem in Matplotlib’s library: Packed Bubble Charts in Python</a></p><p>First look into the dataset and this is what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wePcdu4RyE1avNj-eSM6JQ.png" /><figcaption>Dataframe snippet. Picture by author</figcaption></figure><p>The content is based on available data in each listing URL, and it contains rows for each listing and 75 columns that detail from description, neighbourhood, and number of bedrooms, to ratings, minimum number of nights and price.</p><p>As mentioned earlier, even though this dataset has endless potential, I will focus solely on multi-property ownership.</p><ul><li><strong>Data analysis</strong></li></ul><p>After downloading the data, there’s little data cleaning to do:</p><p>1- Filtering “property_type” to only “Entire rental units” to filter out room listings.</p><p>2- Filtering “has_availability” to “t”(True) to remove non-active listings.</p><pre>import polars as pl<br>#I renamed the listings.csv.gz file to cityname_listings.csv.gz.<br>df=pl.read_csv(&#39;barcelona_listings.csv.gz&#39;)<br>df=df.filter((pl.col(&#39;property_type&#39;)==&quot;Entire rental unit&quot;)&amp;(pl.col(&#39;has_availability&#39;)==&quot;t&quot;))</pre><p>For data processing, I transformed the original data into a different structure that would allow me to quantify how many listings in the dataset are owned by the same host. Or, rephrased, what percentage of the city listings are owned by multi-property hosts. This is how I approached it:</p><ul><li>Performed a value_counts on the “host_id” column to count how many listings are owned by the same host id.</li><li>Created 5 different bins to quantify multi-property levels: 1 property, 2 properties, +2 properties, +5 properties, +10 properties and +100 properties.</li><li>Performed a polars.cut to bin the count of listings per host_id (continuous value) into my discrete categories (bins)</li></ul><pre>host_count=df[&#39;host_id&#39;].value_counts().sort(&#39;count&#39;)<br>breaks = [1,2,5,10,100] <br>labels = [&#39;1&#39;,&#39;2&#39;,&#39;+2&#39;,&#39;+5&#39;,&#39;+10&#39;,&#39;+100&#39;]<br>host_count = host_count.with_columns(<br>    pl.col(&quot;count&quot;).cut(breaks=breaks, labels=labels, left_closed=False).alias(&quot;binned_counts&quot;)<br>)<br>host_count</pre><p>This is the result. Host_id, number of listings, and bin category. Data shown corresponds to the city of Barcelona.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*4jiDRBh7rki1k4WNMFMdqA.png" /><figcaption>Binned listings counts. Image by author</figcaption></figure><blockquote>Please take a second to realise that host id 346367515 (last on the list) owns 406 listings? Is the airbnb community feeling starting to feel like an illusion at this point?</blockquote><p>To get a city general view, independent of the host_id, I joined the host_count dataframe with the original df to match each listing to the correct multi-property label. Afterwards, all that is left is a simple value_counts() on each property label to get the total number of listings that fall under that category.</p><p>I also added a percentage column to quantify the weight of each label</p><pre>df=df.join(host_count,on=&#39;host_id&#39;,how=&#39;left&#39;)<br><br>graph_data=df[&#39;binned_counts&#39;].value_counts().sort(&#39;binned_counts&#39;)<br>total_sum=graph_data[&#39;count&#39;].sum()<br>graph_data=graph_data.with_columns(((pl.col(&#39;count&#39;)/total_sum)*100).round().cast(pl.Int32).alias(&#39;percentage&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*6nyTGiAcjyCbaxkZetSpFw.png" /><figcaption>final data result. Image by author</figcaption></figure><p>Don’t worry, I am a visual person too, here’s the graph representation of the table:</p><pre>import plotly.express as px<br><br>palette=[&quot;#537c78&quot;,&quot;#7ba591&quot;,&quot;#cc222b&quot;,&quot;#f15b4c&quot;,&quot;#faa41b&quot;,&quot;#ffd45b&quot;]<br><br># I wrote the text_annotation manually cause I like modifying the x position<br>text_annotation=[&#39;19%&#39;,&#39;7%&#39;,&#39;10%&#39;,&#39;10%&#39;,&#39;37%&#39;,&#39;17%&#39;]<br>text_annotation_xpos=[17,5,8,8,35,15]<br>text_annotation_ypos=[5,4,3,2,1,0]<br>annotations_text=[<br>    dict(x=x,y=y,text=text,showarrow=False,font=dict(color=&quot;white&quot;,weight=&#39;bold&#39;,size=20))<br>    for x,y,text in zip(text_annotation_xpos,text_annotation_ypos,text_annotation)<br>    <br>]<br><br>fig = px.bar(graph_data, x=&quot;percentage&quot;,y=&#39;binned_counts&#39;,orientation=&#39;h&#39;,color=&#39;binned_counts&#39;,<br>             color_discrete_sequence=palette,<br>            category_orders={&quot;binned_counts&quot;: [&quot;1&quot;, &quot;2&quot;, &quot;+2&quot;,&quot;+5&quot;,&quot;+10&quot;,&quot;+100&quot;]}<br>            )<br>fig.update_layout(<br>    height=700,<br>    width=1100,<br>    template=&#39;plotly_white&#39;,<br>    annotations=annotations_text,<br>    xaxis_title=&quot;% of listings&quot;,<br>    yaxis_title=&quot;Number of listings owned by the same host&quot;,<br>    title=dict(text=&quot;Prevalence of multi-property in Barcelona&#39;s airbnb listings&lt;br&gt;&lt;sup&gt;% of airbnb listings in Barcelona owned by multiproperty hosts&lt;/sup&gt;&quot;,font=dict(size=30)),<br>    font=dict(<br>        family=&quot;Franklin Gothic&quot;),<br>    legend=dict(<br>        orientation=&#39;h&#39;,<br>        x=0.5,<br>        y=-0.125,<br>        xanchor=&#39;center&#39;,<br>        yanchor=&#39;bottom&#39;,<br>        title=&quot;Number of properties per host&quot;<br>    ))<br><br>fig.update_yaxes(anchor=&#39;free&#39;,shift=-10,<br>                tickfont=dict(size=18,weight=&#39;normal&#39;))<br><br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cO0B9XTB0rKlpsFioURHpg.png" /><figcaption>Multiproperty in Barcelona’s Airbnb. Image by author</figcaption></figure><p>Back to the question at the beginning: how can I conclude that the Airbnb essence is lost in Barcelona?</p><ul><li>Most listings (<strong>64%</strong>) are owned by hosts with more than 5 properties. A significant <strong>17% </strong>of listings are managed by hosts who own more than 100 properties</li><li>Only <strong>26%</strong> of listings belong to hosts with just 1 or 2 properties.</li></ul><p>If you wish to analyse more than one city at the same time, you can use a function that performs all cleaning and processing at once:</p><pre>import polars as pl<br><br>def airbnb_per_host(file,ptype,neighbourhood):<br>    df=pl.read_csv(file)<br>    if neighbourhood:<br>        df=df.filter((pl.col(&#39;property_type&#39;)==ptype)&amp;(pl.col(&#39;neighbourhood_group_cleansed&#39;)==neighbourhood)&amp;<br>                    (pl.col(&#39;has_availability&#39;)==&quot;t&quot;))<br>    else:<br>        df=df.filter((pl.col(&#39;property_type&#39;)==ptype)&amp;(pl.col(&#39;has_availability&#39;)==&quot;t&quot;))<br><br>    host_count=df[&#39;host_id&#39;].value_counts().sort(&#39;count&#39;)<br>    breaks=[1,2,5,10,100] <br>    labels=[&#39;1&#39;,&#39;2&#39;,&#39;+2&#39;,&#39;+5&#39;,&#39;+10&#39;,&#39;+100&#39;]<br>    host_count = host_count.with_columns(<br>    pl.col(&quot;count&quot;).cut(breaks=breaks, labels=labels, left_closed=False).alias(&quot;binned_counts&quot;))<br><br>    df=df.join(host_count,on=&#39;host_id&#39;,how=&#39;left&#39;)<br><br>    graph_data=df[&#39;binned_counts&#39;].value_counts().sort(&#39;binned_counts&#39;)<br>    total_sum=graph_data[&#39;count&#39;].sum()<br>    graph_data=graph_data.with_columns(((pl.col(&#39;count&#39;)/total_sum)*100).alias(&#39;percentage&#39;))<br><br>    return graph_data</pre><p>And then run it for every city in your folder:</p><pre>import os<br>import glob<br> <br># please remember that I renamed my files to : cityname_listings.csv.gz<br>df_combined = pl.DataFrame({<br>        &quot;binned_counts&quot;: pl.Series(dtype=pl.Categorical),<br>        &quot;count&quot;: pl.Series(dtype=pl.UInt32),<br>        &quot;percentage&quot;: pl.Series(dtype=pl.Float64),<br>        &quot;city&quot;:pl.Series(dtype=pl.String)<br>    })<br><br>city_files =glob.glob(&quot;*.csv.gz&quot;)<br><br>for file in city_files:<br>    file_name=os.path.basename(file)<br>    city=file_name.split(&#39;_&#39;)[0]<br>    print(&#39;Scanning started for ---&gt;&#39;,city)<br>    <br>    data=airbnb_per_host(file,&#39;Entire rental unit&#39;,None)<br>        <br>    data=data.with_columns(pl.lit(city.capitalize()).alias(&quot;city&quot;))<br><br>    df_combined = pl.concat([df_combined, data], how=&quot;vertical&quot;)<br><br>print(&#39;Finished scanning of &#39; +str(len(city_files)) +&#39; cities&#39;)</pre><p>Check out my GitHub repository for the code to build this graph since it’s a bit too long to attach here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uS9mw3iXzafufkmuj68fYA.png" /><figcaption>Final comparison graph. Image by Author</figcaption></figure><p><a href="https://github.com/gopean-art/Airbnb-analysis">GitHub - gopean-art/Airbnb-analysis: airbnb article</a></p><p>And that’s it!</p><p>Let me know your thoughts in the comments and, in the meantime, I wish you a very fulfilling and authentic Airbnb experience in your next stay 😉</p><p><em>All images and code in this article are by the author</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94407a32679c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/who-really-owns-the-airbnbs-youre-booking-marketing-perception-vs-data-analytics-reality-94407a32679c">Who Really Owns the Airbnbs You’re Booking? — Marketing Perception vs Data Analytics Reality</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I found a hidden gem in Matplotlib’s library: Packed Bubble Charts in Python]]></title>
            <link>https://medium.com/data-science/i-found-a-hidden-gem-in-matplotlibs-library-packed-bubble-charts-in-python-d0f5d892beb7?source=rss-6b453743a21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0f5d892beb7</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Anna Gordun Peiro]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 00:02:41 GMT</pubDate>
            <atom:updated>2024-07-28T00:23:06.678Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ever wished to design those beautiful Tableau based packed bubble charts? Follow along for a tutorial on the <em>Matplotlib</em> solution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*S6VkCD3s72MhxCI4qskyWQ.png" /><figcaption>Bubble chart illustrating women’s participation share at the 2020 Summer Olympics</figcaption></figure><h3>What are packed bubble charts?</h3><p>Packed bubble charts are used to display data in a cluster of circles. Each entry is displayed as an individual circle and two main variables can be used: size of the bubbles and colour.</p><p>Here are some of my favourite packed bubble charts:</p><p><strong>Ukraine grain exports</strong>: Colour used to display country income group and bubble size as tonnes of grain.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/AFP/status/1633842576376643584&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0df726e467e0adebd40b56fb3e394d1/href">https://medium.com/media/c0df726e467e0adebd40b56fb3e394d1/href</a></iframe><p><strong>Essential and Frontline Workers: </strong>Colour used to define group of workers, bubble size as number of workers and clusters for industry sectors</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/mathisonian/status/1335330161701613568&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/8920d7a84ab2298477d49d53151c8055/href">https://medium.com/media/8920d7a84ab2298477d49d53151c8055/href</a></iframe><p>While these examples haven’t been done with Python, would it be possible to build a simpler packed bubble chart only using Matplotlib? Let’s see how:</p><h3><strong>Python code for Bubble charts</strong></h3><p>Last week, I randomly came across an example on the miscellaneous section of Matplotlib’s documentation <a href="https://matplotlib.org/stable/gallery/misc/packed_bubbles.html">[Link]</a> .</p><blockquote>Is this a hidden gem in the Matplotlib’s misc. documentation section?</blockquote><p>Here is the example that came with the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*3YIrxJ6IVRGxfmp01RrVLg.png" /><figcaption>Bubble chart tutorial example</figcaption></figure><h3><strong>How does it work?</strong></h3><p>Surprisingly frictionless to use, here is how to create your first bubble chart</p><pre>#ADD YOUR DATA HERE<br>browser_market_share = {<br>    &#39;browsers&#39;: [&#39;firefox&#39;, &#39;chrome&#39;, &#39;safari&#39;, &#39;edge&#39;, &#39;ie&#39;, &#39;opera&#39;],<br>    &#39;market_share&#39;: [8.61, 69.55, 8.36, 4.12, 2.76, 2.43],<br>    &#39;color&#39;: [&#39;#5A69AF&#39;, &#39;#579E65&#39;, &#39;#F9C784&#39;, &#39;#FC944A&#39;, &#39;#F24C00&#39;, &#39;#00B825&#39;]<br>}<br>#STEP 3<br>bubble_chart = BubbleChart(area=browser_market_share[&#39;market_share&#39;],<br>                           bubble_spacing=0.1)<br>#STEP 4<br>bubble_chart.collapse()<br><br>#STEP 5<br><br>fig, ax = plt.subplots(subplot_kw=dict(aspect=&quot;equal&quot;))<br>bubble_chart.plot(<br>    ax, browser_market_share[&#39;browsers&#39;], browser_market_share[&#39;color&#39;])<br>ax.axis(&quot;off&quot;)<br>ax.relim()<br>ax.autoscale_view()<br>ax.set_title(&#39;Browser market share&#39;)<br><br>plt.show()</pre><p>1- Add your own data or use the one provided in the example. You need one variable for bubble size, another one for the labels and colours.</p><p>2- Copy&amp;paste&amp;run all functions in the code provided</p><p>3- Create your bubble distribution by calling <em>BubbleChart</em> with bubble size as variable</p><p>4- Collapse all bubbles so they are tangents to each other but without crashing</p><p>5- Create chart and add colours, labels and title.</p><p><strong>Important:</strong></p><ul><li>Aspect has to be kept as <em>equal, </em>or your bubbles won’t be perfect circles.</li><li><em>relim</em>() and <em>autoscale_view</em>() have to be kept as well, since you can’t choose where in the grid your bubbles will appear</li></ul><blockquote>I agree that it doesn’t look the best, especially after seeing those beautiful examples that we saw earlier.So I’ve spent a couple of days turning it into something better and here is how:</blockquote><h3><strong>Chart customisation:</strong></h3><p>For my chart, I am using an Olympic Historical Dataset from Olympedia.org which Joseph Cheng shared in <a href="https://www.kaggle.com/datasets/josephcheng123456/olympic-historical-dataset-from-olympediaorg">Kaggle</a> with a public domain license.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*2aX4R3SiSMm-hZRU5_NMVQ.png" /><figcaption>Screenshot of dataset</figcaption></figure><p>It contains event to Athlete level Olympic Games Results from Athens 1896 to Beijing 2022. After an EDA (Exploratory Data Analysis) I transformed it into a dataset that details the number of female athletes in each sport/event per year. My bubble chart idea is to show which sports have a 50/50 female to male ratio athletes and how it has evolved during time.</p><p>My plotting data is composed of two different datasets, one for each year: <strong>2020</strong> and <strong>1996</strong>. For each dataset I’ve computed the total sum of athletes that participated to each event <em>(athlete_sum)</em> and how much that sum represents compared to the number of total athletes (male + female) <em>(difference)</em>. See a screenshot of the data below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*Och6FjobkHIKzJRFTX-Y6g.png" /><figcaption>Screen shot of plotting dataset</figcaption></figure><p>This is my approach to visualise it:</p><ul><li><strong>Size proportion. </strong>Using radius of bubbles to compare number athletes per sport. Bigger bubbles will represent highly competitive events, such as Athletics</li><li><strong>Multi variable interpretation</strong>. Making use of colours to represent female representation. Light green bubbles will represent events with a 50/50 split, such as Hockey.</li></ul><p>Here is my starting point (using the code and approach from above):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*PzE3XmQjAnvNNcx1L1BCAA.png" /><figcaption>First result</figcaption></figure><p>Some easy fixes: increasing figure size and changing labels to empty if the size isn’t over 250 to avoid having words outside bubbles.</p><pre>fig, ax = plt.subplots(figsize=(12,8),subplot_kw=dict(aspect=&quot;equal&quot;))<br><br>#Labels edited directly in dataset<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*9cEQGvkFvM4aP5kls9zJtA.png" /><figcaption>Second result</figcaption></figure><p>Well, now at least it’s readable. But, why is <em>Athletics </em>pink<em> </em>and<em> Boxing </em>blue<em>? </em>Let’s add a legend to illustrate the relationship between colours and female representation.</p><blockquote>Because it’s not your regular barplot chart, <em>plt.legend()</em> doesn’t do the trick here.</blockquote><p>Using matplotlib Annotation Bbox we can create rectangles (or circles) to show meaning behind each colour. We can also do the same thing to show a bubble scale.</p><pre>import matplotlib.pyplot as plt<br>from matplotlib.offsetbox import (AnnotationBbox, DrawingArea,<br>                                  TextArea,HPacker)<br>from matplotlib.patches import Circle,Rectangle<br><br># This is an example for one section of the legend<br><br># Define where the annotation (legend) will be<br>xy = [50, 128]<br><br># Create your colored rectangle or circle<br>da = DrawingArea(20, 20, 0, 0)<br>p = Rectangle((10 ,10),10,10,color=&quot;#fc8d62ff&quot;)<br>da.add_artist(p)<br><br># Add text <br><br>text = TextArea(&quot;20%&quot;, textprops=dict(color=&quot;#fc8d62ff&quot;, size=14,fontweight=&#39;bold&#39;))<br><br># Combine rectangle and text<br>vbox = HPacker(children=[da, text], align=&quot;top&quot;, pad=0, sep=3)<br><br># Annotate both in a box (change alpha if you want to see the box)<br>ab = AnnotationBbox(vbox, xy,<br>                    xybox=(1.005, xy[1]),<br>                    xycoords=&#39;data&#39;,<br>                    boxcoords=(&quot;axes fraction&quot;, &quot;data&quot;),<br>                    box_alignment=(0.2, 0.5),<br>                    bboxprops=dict(alpha=0)<br>                    )<br>#Add to your bubble chart<br>ax.add_artist(ab)</pre><p>I’ve also added a subtitle and a text description under the chart just by using <em>plt.text()</em></p><h3>And ta-da:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*S6VkCD3s72MhxCI4qskyWQ.png" /><figcaption>Final visualisation</figcaption></figure><p>Straightforward and user friendly interpretations of the graph:</p><ul><li>Majority of bubbles are light green → green means 50% females → majority of Olympic competitions have an even 50/50 female to male split <em>(yay🙌)</em></li><li>Only one sport (Baseball), in dark green colour, has no female participation.</li><li>3 sports have only female participation but the number of athletes is fairly low.</li><li>The biggest sports in terms of athlete number (Swimming, Athletics and Gymnastics) are very close to having a 50/50 split</li></ul><h3>Bonus visualisation.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EpouQIQcIvXmmsA9759XgA.jpeg" /><figcaption>Comparison between 2020 and 1996 female participation share</figcaption></figure><p>Here I am using packed bubble charts to illustrate an additional variable: <strong>time</strong>. The chart to the left represents the Olympic games’ participation in <strong>2020</strong> and the one to the right the games in <strong>1996</strong>. Putting them side to side brings on some interesting insights:</p><ul><li>Way more bubbles on the left compared to the right → More sports in 2020 Olympics compared to the 1996 Olympics</li><li>Barely any light green bubbles in 1996 Olympics → Female participation in 1996 was much lower than in 2020 and very far from a 50/50 split</li><li>Boxing had a 0% female participation in 1996 ( dark green) and a 30% female participation in 2020 (blue).</li></ul><p>Visualising and comparing two datasets can be complex, especially when there are three variables that have to be compared at the same time. However, packed bubble charts will captivate your audience, not only with their visual appeal but also with their ease of use and intuitive understanding.</p><blockquote>I’ve also collected a few other customisation options that I haven’t used, check them out below.</blockquote><h3><strong>Other customisations</strong></h3><p>Increase bubble_spacing for a more relaxed view (2 vs 0.1)</p><pre>bubble_chart = BubbleChart(area=browser_market_share[&#39;market_share&#39;],<br>                           bubble_spacing=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*pFxE4dJARZWG3O2aEi_7Ig.jpeg" /><figcaption>effect of bubble spacing</figcaption></figure><p>It’s also possible to obtain a horizontal view only by updating def_init. The modification calculates the new x coordinates for each bubble computed with their and past bubbles radius and bubble spacing. Y coordinates are set to 0.</p><pre> def __init__(self, area, bubble_spacing=0):<br>        area = np.asarray(area)<br>        r = np.sqrt(area / np.pi)<br><br>        self.bubble_spacing = bubble_spacing<br>        self.bubbles = np.ones((len(area), 4))<br>        self.bubbles[:, 2] = r<br>        self.bubbles[:, 3] = area<br><br>        # UPDATE: Position the bubbles in a horizontal row, touching each other<br>        self.bubbles[:, 0] = np.cumsum(r * 2 + self.bubble_spacing) - r - self.bubble_spacing / 2<br>        self.bubbles[:, 1] = 0  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*fRxgR2eyNMFhenauGdAW4Q.png" /><figcaption>Horizontal customisation</figcaption></figure><h3>Potential improvements✨</h3><p>I’d love to see something similar done in Plotly since this graph is screaming for some interactivity (especially for the bubbles that are too small to have a label) and maybe a slider to change years and update the graph automatically.</p><h3>Final points</h3><p>The matplotlib’s little gem solution for packed bubble charts will save you hours of circle drawing and has great potential of becoming a powerful alternative to Tableau. In this article, we have explored how to create them, customise them and add legends. By the end of it, we have obtained a final visualisation with visual appeal, ease of reading and that allows you to tell a story and captivate your audience.</p><p>I’ve also given you a little flavour of gender equality at the Olympic games and how fast it has improved in the past 20 years.</p><blockquote>Fyi, Paris 2024 will be the first time in history where we will see an equal number of female/male participants</blockquote><p>Happy coding and Olympic watching!</p><p><em>All images in this article are by the author</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0f5d892beb7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/i-found-a-hidden-gem-in-matplotlibs-library-packed-bubble-charts-in-python-d0f5d892beb7">I found a hidden gem in Matplotlib’s library: Packed Bubble Charts in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>