fabiochiu/medium-articles huggingface dataset:
Texts, Fonts, and Annotations with Python’s Matplotlib
By: Thiago Carvalho
Tags: Text, Data Visualization, Annotations, Matplotlib, Python

Some examples of titles:

Regardless of why or how. The elements used to inform our audience about the content of our chart are almost the same.

We need a title, which is the text with the largest font, usually placed at the top of the chart.

Subtitles are not required but are very helpful. They are placed below the title with a smaller font and are very versatile. They can describe the chart, highlight some information, or add details such as where, how, or when.

Captions can display information about our data source, notes, or any other relevant information.

Axis labels are required when the information on our axis is not explicit. Dates, years, or categories are usually relatively easy to understand and might not require labels.

fig, ax = plt.subplots(1, figsize=(11,6)) plt.plot(date, spam, color='#C62C1D', lw=2.5, marker='o')

plt.ylim(0,400) # remove spines

ax.spines['right'].set_visible(False)

ax.spines['top'].set_visible(False) # grid

ax.set_axisbelow(True)

ax.yaxis.grid(color='gray', linestyle='dashed', alpha=0.3)

ax.xaxis.grid(color='gray', linestyle='dashed', alpha=0.3)

plt.suptitle('Global volume of spam e-mail', x=0.125, y=0.98, ha='left', fontsize=18)

# SUBTITLE

plt.title('Daily average by month', loc='left', fontsize=14)

# AXIS LABELS

plt.ylabel('Billions')

plt.xlabel('2020')

# CAPTION

plt.text(-0.5, -60, 'Source: Cisco, # TITLEplt.suptitle('Global volume of spam e-mail', x=0.125, y=0.98, ha='left', fontsize=18)# SUBTITLEplt.title('Daily average by month', loc='left', fontsize=14)# AXIS LABELSplt.ylabel('Billions')plt.xlabel('2020')# CAPTIONplt.text(-0.5, -60, 'Source: Cisco, https://talosintelligence.com/reputation_center/email_rep' , ha='left', fontsize = 11, alpha=0.9) plt.show()

Chart with text — Image by the author

Matplotlib doesn’t have a method for each text element, but that’s nothing we can’t handle.

If you only require a title, you can use the .title() function. That will position a text at the top of the chart with a larger font, and then you can use the parameters to change its position, size, color, and so on.

It gets more complicated when we need a subtitle. My preferred method is to use .suptitle() for the title, .title() for the subtitle, and .text() for the caption.

Suptitle is a title for the figure — You can only have one per figure, so this method doesn’t work with subplots.

By default, suptitle is plotted at the top center, and unlike the title, there is no easy way to position it at the left or right of the chart.

Centred title — Image by the author

I like using .suptitle() because the code feels a little more organized.
Interpreting Data through Visualization with Python Matplotlib
By: Saptashwa Bhattacharyya
Tags: Data Visualization, Pandas, Data Science, Matplotlib, Python

In plt.scatter s and c represent the size and color of the the markers. Particularly for this plot to represent Indian immigrants, I’ve made use of both these parameters. Here s is the normalized value of immigrants over the years (multiplied by 2000 so that the marker sizes are big enough) and c, cmap represent just the raw number of immigrants. So higher the number of immigrants is represented by blue and opposite with purple.

World Map : folium.Map()

One very gripping part of the course was using Folium library, which helps to create several types of interactive Leaflet maps. We will see using the same immigration data-set, how well one can represent some crucial information in the World Map. First we get started with installing Folium.

pip install Folium

print folium.__version__ # check the version >> 0.7.0

The special kind of map we are interested in are called Choropleth. It’s a kind of thematic map where the portion of the map is shaded/patterned according to the proportion of the statistical variable used. Here, I will plot how the number of immigrants varied from all over the world from the year 1985 to the year 2005. The pie plot we have seen before for continents, can be used to complement this Choropleth map.

Now to create a Choropleth map we need a .json file containing the border coordinates of all countries and this file is provided by IBM, which you can get from my GitHub. With this I used the code snippet below to plot a choropleth map of immigrants all over the world in 1985. This maps are interactive so you can zoom in or out but here I just show a screenshot —
Tweets Data Visualization with Circles and User Interaction
By: Arief Anbiya
Tags: Statistics, Data Visualization, Science, Matplotlib, Geometry

The Model

A circle will be used to represent a tweet. The color transparency of the circle will reflect the number of retweets of the tweet (could also be the number of likes, depending on your interest). Circles with strong color represent tweets with high number of retweets. Circles with high transparency are tweets with low number of retweets. Among all the tweets in the dataset, there must be a tweet that has the highest number of retweets, that tweet will be represented by a circle without transparency. So only tweets that have the highest number of retweets will have color with no transparency. All the other tweets in the dataset will have more transparency.

So far, we have only added one measurement to the visualization: the number of retweets (or number of likes). But we can utilize another property of a circle, that is the size (radius). Now what will the size represents? there are many options..but let us pick one. By default, all circles will have radius 1, but if a tweet has more likes than retweets, then we will set the circle to have radius 2. This way, our eyes can easily differentiate which tweets that have more likes than retweets.

Now how should we organize the circles? we could just scattered the circles in the plot, but that would look messy and circles may overlap each other. We could just put the circles in scatter plot (with x and y axis represent two additional measurements), but circles may also overlap each other. So, what we want is that no two circles overlapping each other. This needs us to write our own algorithm. For our case, we will use an algorithm similar to the circle packing algorithm (general example & specific example). The position of the circles will be random but centered and will be made as compact as possible.

Here is an example with very low samples (for simplicity):

Visualization with small samples (5 tweets for each account)

The above image is an example of the visualization using small samples (5 tweets) from Sadiq Khan (Mayor of London), Donald Trump (President of USA), Prabowo Subianto (Indonesian Presidential Candidate), and Joko Widodo (President of Indonesia) twitter accounts. The tweets from Khan and Trump are collected on 25 Nov 2018, and the tweets from Prabowo and Jokowi are collected on 22 Nov 2018. We can easily see that tweets from Donald Trump have more reactions than the others. There is only one tweet that has more retweets than likes, and it is from Sadiq Khan. Here are the snapshots of the 2 tweets (one from Trump, and the other from Sadiq Khan):

The number of retweets and likes on the image are already updated. (this image is captured on 1 Feb 2019)

At the time of collection, the number of likes is 0 and the number of retweets is 38. The tweet was retweeted by Sadiq Khan. (this image is captured on 1 Feb 2019)

The 5 tweets from each of Sadiq Khan and Prabowo Subianto are not famous, since the color of the circles are very close to white (very transparent).
Matplotlib package: Plot your data
By: Bala Kowsalya
Tags: Data Visualization, Data Science, Analytics, Matplotlib, Python

Walkthrough: Basics of Matplotlib

Welcome to our tutorial series Day #7 to play with the basics of Matplotlib and create cool graphs. Using Matplotlib, we can create most kinds of charts such as line graphs, bar charts, scatter plots, pie charts, stack plots, histogram, 3D graphs, geographic map and etc.

Content

Installing and importing the package

Creating basic graphs

Markers, Linestyles and Color codes

Axes limits

Labeling plots

Install/Import Pandas

You can install Pandas by running the below command in Anaconda Prompt,

conda install matplotlib

For those who don’t have Anaconda installed in your machine, you can install it from the terminal using,

pip install matplotlib

Once installed, launch Jupyter Notebook and get started.

You can verify the installation by checking the version of the package and importing it.

import matplotlib.pyplot as plt

This line imports the integral pyplot which we are going to use now, we import it as plt, just a traditional naming convention in Python. If you have executed the above statement without any error, cool. Now, you have imported the package to use it further.

Let's create a graph!

Now we shall create a figure and axes without any plots.

fig = plt.figure()

ax = plt.axes()

Here, a figure can be imagined as a single container that contains all the objects and axes as a boundary box within which we plot data. An empty graph without any plots will look like,

Now, we have created axes and ready to plot some data in it.

.plot() is used to plot the coordinates. This function inputs several parameters to customize the graph. Among all, the mandatory parameters are ‘x’ and ‘y’ coordinates. For this, we are going to pass lists. This will plot the graph in the background, to show it on screen, we need to use .show()

plt.plot([1,2,3],[3,5,4])

plt.show()

Cool! We got it. If we have multiple data lines in our graph, matplotlib will automatically paint them in different colors to make it easier to visualize, now its only blue and it looks so plain right. Let’s add some properties to make it vibrant.

Markers, Line Colors and Styles

As I said earlier, plot() inputs several parameters to customize the graph.

import numpy as np

x = np.linspace(0, 10, 1000)

plt.plot(x, np.cos(x))

plt.show()

Color code

We can apply needed color to lines in the graph. The color can be specified in a variety of ways,
WordCloud in Hindi Using Python + Matplotlib
By: Rupesh Gondaliya
Tags: Data Visualization, Hindi, Word Cloud, Matplotlib, Python

A Wordcloud (or Tag cloud) is a visual representation of text data. It displays a list of words, the importance of each beeing shown with font size or color.

This format is useful for quickly perceiving the most prominent terms. Python is totally adapted to draw this kind of representation, thanks to the wordcloud library developed by Andreas Mueller.

so,we found lot’s of tutorial related to English text and Some Other Language

In This article we have see that how to work with wordcloud with Hindi Text using python and matplotlib

Hindi WordCloud

Let’s see :-

#Import Library

import matplotlib.pyplot as plt

from wordcloud import WordCloud, STOPWORDS

from nltk.tokenize import word_tokenize

import re

stopword=open(“stopwords.txt”,’r’)

stop_words=[]

# pre-process stopword

for i in stopword:

i = re.sub(‘[

]’, ‘’, i)

stop_words.append(i)

stopwords = set(stop_words)

text = “एक बार की बात कहता हूँ मित्र बाजार गए तो थे कोई एक मामूली चीज लेनेपर लौटे तो एकदम बहुत से बंडल पास थे मैंने कहा यह क्या बोले यह जो साथ

थीं उनका आशय था कि यह पत्नी की महिमा है उस महिमा का मैं कायल हूँ आदिकाल

से इस विषय में पति से पत्नी की ही प्रमुखता प्रमाणित है और यह व्यक्तित्व

का प्रश्न नहीं स्त्रीत्व का प्रश्न है स्त्री माया न जोड़े तो क्या मैं

जोडूँ फिर भू सच सच है और वह यह कि इस बात में पत्नी की ओट ली जाती है मूल

में एक और तत्तव की महिमा सविशेष है यह तत्व है मनीबैग अर्थात् पैसे की

गरमी या एनर्जी पैसा पावर है पर उसके सबूत में आस पास माल टाल न जमा हो तो

क्या वह खाक पावर है पैसे को देखने के लिए बैंक हिसाब देखिए पर माल असबाब

मकान कोठी तो अनदेखे भी दीखते हैं पैसे की उस पर्चेजिंग पॉवर के प्रयोग

में ही पावर का रहस्य है लेकिन यही नहीं लोग संयमी भी होते हैं वे फिजूल

सामान को फिजूल समझते हैं वे पैसा बहाते नहीं हैं और बुद्धिमान होते हैं “

wordcloud = WordCloud(font_path=’Lohit-Devanagari.ttf’,width = 800, height = 800,

background_color =’white’,

stopwords = stopwords,

min_font_size = 10).generate(text)



# plot the WordCloud image

plt.figure(figsize = (8, 8), facecolor = None)

plt.imshow(wordcloud)

plt.axis(“off”)

plt.tight_layout(pad = 0)



plt.show()

Here Hindi StopWord download to here and Hindi Font download to here
Analysis of New York MTA Turnstile Data
By: Noah Junyoung Lee
Tags: Pandas, Turnstile, Matplotlib, Python, Seaborn

Data Cleaning:

The MTA opens their turnstile data to the public and can be downloaded for free here. Here are the different variables found in the dataset:

C/A = Control Area

UNIT = Remote Unit for a station

SCP = Subunit Channel Position represents an specific address for a device

STATION = Represents the station name the device is located at

LINENAME = Represents all train lines that can be boarded at this station

DIVISION = Represents the Line originally the station belonged to BMT, IRT, or IND

DATE = Represents the date (MM-DD-YY)

TIME = Represents the time (hh:mm:ss) for a scheduled audit event

DESc = Represent the “REGULAR” scheduled audit event (Normally occurs every 4 hours)

ENTRIES = The cumulative entry register value for a device

EXIT = The cumulative exit register value for a device

For this project we used the turnstile data from 2016 to 2018 for the months from March 1st to June 15th. Notice that Entries and Exit columns are cumulative measures and are measured every four hours. In order to calculate the number of people who went through a specific station in a given four hour interval, we subtracted each rows of the cumulative entries and exits. We will then add the subtracted cumulative entries and exits to form a column for “total number of traffic”.
A list of tools you will need to “play” with data
By: Emem Andy
Tags: Anaconda, Matplotlib, Data Visualization Tools, Python

Now that is out of the way, let’s go straight to the tools needed to “play” with data.

Anaconda

Anaconda is a distribution of Python & R programming that aims to simplify package management and deployment. With Anaconda, you won’t have to keep downloading packages you might need to work with Python as they’re a lot and so Anaconda has all those packages and more to make your life easier.

Jupyter Notebook

This is an open-source web application that enables you to create and share documents that might contain live code, visualizations & narrative text. Its uses are: data cleaning and transformation, numerical stimulation, statistical modeling and many more. You can interact with any code that you write in Jupyter. To know how to use Jupyter, is to know ease lol.

Google Colab

This is basically Jupyter notebook under Google servers. There are a few added features on here but you could do the same things you can on Jupyter and more.

Tableau

Tableau can help anyone see and understand their data. It is a very powerful tool used in the Business Intelligence Industry. In simpler terms, it is a visual analytics engine that makes it easier to create interactive visual analytics in the form of dashboards.

Power BI

Power BI is also a business analytics service, by Microsoft. It aims to provide interactive visualizations and business intelligence capabilities with an interface simple enough for users to create their own reports and dashboards. It truly is simple enough trust me.

Matplotlib

This is an amazing visualization library in Python for 2D plots of arrays. It’s a multi-platform data visualization library built on Numpy arrays. Matplotlib consists of various plots like line, bar, scatter, etc.

Numpy

Numpy is also a library in Python. Numpy is used to work with arrays as it provides a powerful N-dimensional array object. It does so by overriding the lists in Python with its lists because numpy lists are faster.

Pandas

Pandas basically allows you to interact with data as csv files, databases etc. It is used for data manipulation and analysis which is built on top of Python. It makes use of data as dataframes (DF).

In order to acquaint your self with data these are my personal recommendations. In my upcoming blogposts, I’ll be introducing tips and tricks on how to use these tools to interact with data.
Show Categorical Data in Bar Chart using Matplotlib
By: Iroshan Aberathne
Tags: Graph, Data Visualization, Matplotlib, Python

Here, we are going to discuss a procedure to represent a bar chart where each bar represent its’ categorical representation as well.

Refer following code block,

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.patches as mpatches



x_ticks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

graph_one = [10000, 10000, 3000, 4000, 6000, 6000, 5000, 5000, 5000, 3000]

categorical_data = ['CAT-1', 'CAT-2', 'CAT-3', 'CAT-3', 'CAT-1', 'CAT-3', 'CAT-1', 'CAT-1', 'CAT-2', 'CAT-2']



fig = plt.figure(figsize=(25, 15))

heights_graph_one = [x for x, _ in enumerate(graph_one)]



desc_patch = mpatches.Patch(hatch=".", label='CAT-1')

asc_patch = mpatches.Patch(hatch="\\", label='CAT-2')

mid_patch = mpatches.Patch(hatch="-", label='CAT-3')



for x in range(len(x_ticks)):

if categorical_data[x] == 'CAT-1':

pattrn = "."

elif categorical_data[x] == 'CAT-2':

pattrn = "\\"

else:

pattrn = "-"

plt.bar(heights_graph_one[x], graph_one[x], hatch=pattrn, color='blue', edgecolor='black')

plt.xticks(np.arange(0, len(x_ticks), 1), rotation="90")

plt.legend(handles=[desc_patch, asc_patch, mid_patch], loc="upper right", frameon=True, fontsize=12)

plt.ylabel("Value", fontsize=12)

plt.xlabel("Sample", fontsize=12)

plt.title("Bar with Category", fontsize=12)



plt.show()

Fig.1. Bar Chart with Categorical Data

The implementation as simple as that………
Netflix Movies and TV Shows — Data Visualization using Matplotlib
Tags: Data Visualization, Netflix, Matplotlib, Python

Photo by Thibault Penin on Unsplash

Hello There!

Hope you are doing well.

This article deals with Data Exploration and Visualization of Netflix Movies and TV shows using the python library Matplotlib.

We use the dataset of Netflix Movies and TV Shows from Kaggle.

Let’s start by importing the necessary libraries.

The dataset has the following columns:

show_id, type, title, director, cast, country, date added, release_year, rating, duration, listed_in and description

More specifics related to the dataset can be found on the Kaggle dataset page.

The data needs to cleaned before displaying. There could be missing values in the data and they need to be verified beforehand.

netflix_df.isnull().any()

This line will output true or false based on whether the attribute has a missing value. director, cast, country, date_added and rating have missing values. Now, we can either remove those data entries or fill in the missing values. The missing values in director, cast and country can be filled in as Undefined. Missing values of date_added and rating needs to be removed.

The data is all set for visualization.

Data Visualization

The type of content

Let’s start with the type of content provided i.e. Movies and TV Shows. The best way to visualize this is by making use of a pie chart.

It is clear that Netflix mostly concentrates on movies rather than TV Shows.

Content added across the years

Getting a plot for the amount of content added across the years would need a slight bit of data extraction. The year needs to be extracted from the date_added attribute. The data can then be depicted using a line plot.

There is a large increase in the amount of content added starting from the year 2017. The amount of movies added tends to be much more (almost double!) than the amount of TV Shows.

Countries with the Most Titles

Here, a title can have more than one country. The correct number of titles for each country must therefore by determined before plotting the results. Also, undefined data will be excluded. This data will be interpreted using a horizontal bar graph.

United States is leading the chart with a fairly substantial lead over all the other countries.

Count of titles by Rating

The count of movies and TV Shows need to be displayed. The best way to do this is by using a bar plot.

Duration of TV Show

The duration of a TV Show is the number of seasons it spans. In the data set, each data entry is given as “1 Season”, “2 Seasons” and so on. The number needs to be extracted out before plotting the data. A line plot has been used to represent the results.

Major Takeaways from the data

Movies over TV Shows. Short content over long content. The growth of Netflix started in 2014. Since then, the company has grown tremendously.

Thanks for reading!
About CSV
By: Sanjay Sheel
Tags: Machine Learning, Pandas, Csv, Data Science, Matplotlib

Hello all

This is sanjay sheel and today i am writing post for about csv and importance of csv in data science

CSV stand for comma seperated values basically it is a kind of file where you can store various kind of data and can create table in that table you can fill data means in another term

Here the data which we are used to see in the tabular formate. So baciallly it is stored in .csv file and are written by text and in the form of row’s and columns and here the column’s are seperated by using comma this is the main reason why it say’s comma seperated values. means the file that contain various kind of values in row’s and column’s and are seperated by using comma’s

we can create csv file using <name>.csv mean using .csv

1997,skon,usa,india

here i have used jupyter notebook to make csv file here i am giving name of file in this pic i have given name ’’first.csv’’ and first is the name and .csv (dot csv) it is file type and it is the extension to create the csv file

This is how i created the table

you can see it is very simple to create and to see the table just type name or text and make another column by comma that’s it

I have used python and pandas to see csv data

Here is some information of table, row and column if you know so you can skip this

This is very beautiful image to understand table this table i have taken from wiki to make good understanding of table

COLUMN: A column is a set of data values of a particular simple type, one value for each row of the database. A column may contain text values, numbers, or even pointers to files in the operating system ROW: A row is a horizontal group of values in table. It contains values for multiple fields, which are defined by columns. Row’s in the table that also consider as a record ‘s. For example, a row (or record) from a Employee table may contain an employee’s name, position, salary, and other information. TABLE: A table is an arrangement of data in rows and columns, or possibly in a more complex structure. Tables are widely used in communication, research, and data analysis. Tables appear in print media, handwritten notes, computer software, architectural ornamentation, traffic signs, and many other places.

I have given a brief introduction of csv with practical example. So what are you waiting for go and make by your self and follow me to be in touch to read such blog’s in very easy language

for more information you can visit here
Draw a Colorful Coronavirus with Matplotlib
By: Linda Cai
Tags: Outbreak, Art, Matplotlib, Python, Polar

Most people use Matplotlib for data visualization, but YOU can also use it to create graphics, especially if you have time for a new hobby.

Complete with a huge color palette (including CSS color names) and a myriad of markers, Matplotlib provides great value for an aspiring artist.

We will create a crude imitation of the cross-section view of the virus, shown on the right in this diagram:

The code is a few dozen lines of Python which can run in Jupyter notebook. I am using (jupyter==1.0.0, matplotlib 3.1.1, numpy 1.17.2) with Python 3.7.4. The resulting image is all the way at the bottom.

%matplotlib inline

import matplotlib.pyplot as plt

import numpy as np # Overall setup. Remove all labels. Use black background.

bgcolor = (0,0,0)

fig = plt.figure(facecolor=bgcolor, figsize=(10,10))

ax = fig.add_subplot(111, projection='polar')

ax.set_facecolor(bgcolor)

ax.grid(False)

ax.set_yticklabels([])

ax.set_xticklabels(['']) # Designate set of angles at which to place markers

delta = 0.01 # smaller delta for higher resolution

rads = np.arange(0, (2 * np.pi), delta) # Overall parameters

radius = 7

squiggliness = 12

rna_w = 1.8

env_r = radius + rna_w * 1.2

hema_space = 7 # spacing (more means longer HE dimers)

n_hema = 20 # number of hemagglutinin-esterase (HE) dimers # Loop through each angle and add markers per component

for radian in rads:

rna = radius + rna_w * np.sin(squiggliness * radian) # sinusoidal genetic material shape

ax.plot(radian, rna, '.', color='fuchsia')

ax.plot(radian, env_r, 'o', color='crimson') # envelope



hema_rad = (radian * 100 // n_hema) / (100 // n_hema) # angle at which to place HE dimer

displacement = (radian - hema_rad) * hema_space

ax.plot(hema_rad, env_r + displacement, 'v', color='deepskyblue') spike_rad = hema_rad - delta * n_hema / 2 # spike glycoprotein goes in between HE dimers

ax.plot(spike_rad, env_r + displacement, '.', color='gold')

ax.plot(spike_rad, env_r + hema_space * n_hema * delta + displacement, 's', markersize=10, color='gold') # Add the darker red color inside envelope

ax.add_artist(plt.Circle((0,0), 9, color='maroon', transform=ax.transData._b)) plt.show()

The result has a few flaws, and may be rejected from the MoMA, but is probably good enough to become motel bathroom wall art.
Data Visualization Cheat Sheet with Seaborn and Matplotlib (Part 2)
By: Chi Nguyen
Tags: Visualization, Data Visualization, Matplotlib, Seaborn, Data Analysis

Introduction

In my previous post, I introduced some simple visualization tips to quickly build good-looking charts with Seaborn and Matplotlib. Today, I’m gonna show you in detail how to build more complex charts, including combination charts and subplots.

Necessary Package Installation

There are some packages that we should import first.

import numpy as np

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

%matplotlib inline

Data Description

My dataset is collected from Kaggle public dataset and you can easily download via the following link:

https://www.kaggle.com/puneetbhaya/online-retail

Let’s take a look at our dataset. I will use data related to Germany as an example.

Figure 1: Data Frame

Figure 2: Data information

Data Visualization

Combination chart

This type of chart demonstrates multiple variables in different formats on the same chart. Combination chart can be helpful when you want to make comparisons between values in different categories.

As an example, let’s visualize the top 10 product categories in Germany by sales and their corresponding revenues.

Figure 3: Combination Chart

In the above chart, the top 10 categories are displayed through bar chart and their revenues are displayed through line chart. By looking at this combination graph, we can observe some interesting insights.

The most purchased product is not the one that generates the most revenue. Take product 22326 for instance, its unit sold ranks first but its revenue only ranks third.

Although POST is the 3rd most purchased item, it’s the product that generates the most revenue.

22961 is the least purchased product, but its revenue ranks 6th.

Subplots

Subplot helps create multiple plots on a single panel. In this section, I will show you a few ways to make a beautiful graph with multiple plots.

Again, we are using the top 10 product categories in Germany by sales.

Figure 4: Subplot Example

Let’s try to combine 4 plots into a figure.

I’m gonna plot:

Top 10 consumers by product units purchased

Top 10 consumers by amount of money paid

Top 10 product categories that Top 10 consumers purchase, by units

Top 10 product categories that Top 10 consumers pay most money for

But first, let’s prepare some necessary data for our visualization:

Figure 5: Data preparation

Now, let’s transform the information into plots:

Figure 6: Subplot example

Conclusion

These are some of my tips for Seaborn and Matplotlib visualization. These codes are my self-learning notes during my time working as a data analyst. Without a doubt, there are still many aspects that I will need to improve on. However, I hope my notes can help you with your charts in one way or another.
5 Tricks to Improve Bar Graphs: Matplotlib
By: Manmohan Singh
Tags: Data Visualization, Bar Graph, Data Science, Matplotlib, Python Programming

The bar graph is a widely used chart in data science. Charts help you to connect the data with your stakeholders, managers, or audience. Charts speak a story about your results. Your graph should not look messy. It should be clearly visible and easy to understand.

Bar charts popularly represent data that has multiple categories. Create a bar graph in such a way that it creates a meaningful picture of data in your audience’s mind.

A data scientist or data analyst should create a graph that represents data in an impartial way.

In this article, we discuss the best practices to create a highly effective bar graph. Bar graph represents time-series data, ranking, count of different categories, distribution of data, and deviation in data.

Let’s start with the best practices we should follow to create the best bar graphs.

1. Horizontal and Vertical Bar graphs

Graphical representation of categorical data can be done by horizontal or vertical graphs. As a data scientist, we should know when we need horizontal graphs and when we need vertical graphs.

Use a horizontal graph to represent data whose categories label name is not fit under vertical graphs. Also, I will recommend vertical graphs for those data whose categories are less than 7.

Vertical Bar Graph
Setting up M1 mac without homebrew
By: Lu Wang
Tags: TensorFlow, Apple M1 Chip, MacBook Pro, Matplotlib, Python

Recently, I got my new macbook with the M1 chip and I was excited to try out the new features — one of them being using the new version of tensorflow that takes advantage of the new chip. To setup Python so that I can try out this mac, the top ones I need are: numpy, tensorflow, matplotlib, pandas, sklearn.

Of course, before installing anything the very first thing I checked was homebrew. After finding out homebrew has not yet supported the M1 macs yet, I was left with two options 1) get the source and install the dev version with ARM support or 2) install with Rosetta.

I can’t decide which route I wanted to take for that moment so I decided to temporarily fly without homebrew. The good news is that when I got this version of Tensorflow for the M1 chip, it also comes with Numpy. 2/5 tasks completed! I was able to quickly test out some Tensorflow examples on my new mac and the performance was awesome comparing to my old mac.

Then I wanted to make some basic plots and then I realized matplotlib cannot be installed without it’s dependency Pillow and Pillow requires libjpeg. Again, as a consequence of my decision to fly without homebrew, I know it’s going to be bumpy. And I decided to install libjpeg from source rather than simply `brew install libjpeg`.

So I first downloaded the source code for libjpeg.

cd jpeg-9c

./configure --prefix= /usr/local/include

make

make install

Set the paths right

export LDFLAGS="-L /usr/local/include -L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include"

export CPPFLAGS="-I /usr/local/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include"

Then pip install Pillow and matplotlib ran smoothly without any problem.

I still left with pandas and sklearn on my list but I am able to further try out tensorflow on my mac and visualize some results without any problem for now.
FacetGrid vs AxesSubplot Type with Seaborn
By: Bangun M Sagala
Tags: Catplot, Facetgrid, Matplotlib, Seaborn, Relplot

Seaborn is a powerful data visualization library which based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Two types of plot that used are FacetGrid and Axessubplot. While Axessubplot is a single plot of graph drawn at one time, FacetGrid is able to create several subplots in one time based on determined variable. So Firstly, i will explained the difference between those two plot types, then i will going little deeper in FacetGrid, because it will make plot more easily.

Beside seaborn library, we have to import pandas because FacetGrids need to store data in a panda dataframe where each row represents an observation and columns represents variables. We will use “tips” dataset, which is built in dataset in seaborn library.

We will plot, from the same dataset, two scattered diagram by using FacetGrid and AxesSubplot with seaborn libary. The results of the plot are the same, we will just know the type of the plot from its command or we check the type using type command.

AxesSubPlot Type

FacetGrid Type

AxesSubplot type is generated by plotting graph using seaborn library prefix. seaborn.scaterrplot or seaborn.countplot are two examples from this type of plot. We can just generate one plot graph using this type plot at one time. So if we want to create an array of graph or merely single graph we can use facetgrid type.

Facetgrid type is an array of graph that has three dimensions, which are column, row and hue. It is easy and flexible to create subplot using row and column variable. Seaborn catplot or seaborn relplot are samples of facet grid type. Relplot is usually used to plot scattered plot or line plot to create relation between to variable. We can choose type of graph line or scatter by define it at kind variable in relplot command. We can define dimension for column by using col variable and col_wrap to define how many column will be generated.

scatterd plot using relplot sample

Another facetgrid plot is catplot. Catplot or categorical plot involved a categorical variable. Samples of plot using catplot are countplot , bar plot and box plot. Usually those kind of plot used to compare between two groups. Like relplot we can define type of plot wheter count, bar, or box by using kind variable. we can see the sample of box plot using cat plot below.

barplot using catplot command

So after i consider the advantages between two types of plot in seaborn , facetgrid and axessubplot, i prefer to used facetgrid, because it’s more flexible to create plot and easy to generate subplot if it is needed. By using relplot , for relation, and catplot, for comparison, we simply can create visualization from data set that is needed for exploring data or communicating final analyzed data.
Spotify Music Data Analysis: Part 3
By: Pragya Verma
Tags: Data Visualization, Data Science, Matplotlib, Seaborn, Data Analysis

Music Attributes

The dataset gathered in the first article of this series contains the song attributes. Before performing data analysis it is necessary to understand those features individually.

The song attributes in the dataset are explained below:

Tempo: The tempo of the song. The overall estimated tempo of a track in beats per minute (BPM). In musical terminology, the tempo is the speed or pace of a given piece and derives directly from the average beat duration.

Energy: Energy is a measure from 0.0 to 1.0 and represents a perceptual measure of intensity and activity. Typically, energetic tracks feel fast, loud, and noisy. Higher the value more energetic the song.

Danceability: Danceability describes how suitable a track is for dancing based on a combination of musical elements including tempo, rhythm stability, beat strength, and overall regularity. The value ranges from 0 to 1. Higher the value more suitable the song is for dancing.

Loudness: Loudness values are averaged across the entire track. It is the quality of a song. It ranges from -60 to 0 DB. Higher the value, the louder the song.

Valence: A measure from 0.0 to 1.0 describing the musical positiveness conveyed by a track. Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), while tracks with low valence sound more negative (e.g. sad, depressed, angry).

Liveness: Detects the presence of an audience in the recording. Higher liveness values represent an increased probability that the track was performed live. A value above 0.8 provides a strong likelihood that the track is live.

Acousticness: A confidence measure from 0.0 to 1.0 of whether the track is acoustic. 1.0 represents high confidence the track is acoustic.

Speechiness: Speechiness detects the presence of spoken words in a track. The more exclusively speech-like the recording (e.g. talk show, audiobook, poetry), the closer to 1.0 the attribute value. Values above 0.66 describe tracks that are probably made entirely of spoken words. Values between 0.33 and 0.66 describe tracks that may contain both music and speech, either in sections or layered, including such cases as rap music. Values below 0.33 most likely represent music and other non-speech-like tracks.

Mode: Songs can be classified as major and minor. 1.0 represents major mode and 0 represents minor.

Key: Key is the pitch, notes or scale of song that forms the basis of a song. 12 keys are ranging from 0 to 11.
Gold Price Prediction using Machine Learning with Python
By: Mohammad Sakib Mahmood
Tags: Machine Learning, Scikit Learn, Pandas, Matplotlib, Python

Gold has always held a prominent place in every country’s economy and among the people. In this article, I will introduce machine learning on Gold Price Prediction with Python language.

Gold Price Prediction

Gold prices have historically skyrocketed, peaking at $ 1,800 in 2020. These swings that gold has faced can be attributed to several events that occurred during the period. Stock prices are strongly correlated with public information and world events, and gold is no exception. Unlike other financial assets, precious metals behave positively in times of crisis. Indeed, in the face of events such as epidemics, wars, and economic disruption, most assets experience a decline in their value. However, in search of cover, investors are turning their attention to gold. As a result, the demand for yellow metal increases, resulting in a rise in the market valuation. Gold tends to be viewed as a strategic and tactical investment asset when considering portfolio diversification. However, the economic and financial aspects are not the only factors that can affect gold prices. Geopolitical factors may also influence the valuation of the yellow metal market. Indeed, show that faced with geopolitical risks, gold acts as a safe haven. In fact, he has an affirmative reaction in times of threats resulting from geopolitical and international tensions. By analyzing financial, geopolitical, and global data on natural disasters, it is possible to predict future fluctuations in the price of gold, which will allow investors to improve the management of their portfolios in the face of unexpected movements. of the market.

In this section, I will take you through a Machine Learning tutorial on Gold Price Prediction with Python. I will start the task of Gold price prediction by importing the necessary Python libraries and the dataset:

Now do some data preparation to fit the data properly in the machine learning model:

Linear Regression algorithm:

Now as I have prepared the data to fit in a machine learning model for the task of gold price prediction, the next step is to choose a machine learning algorithm.

And then plot the results of gold price prediction that i got from the linear regression algorithm:

For Euro, we can follow the same procedure in the below
Test Cricket Trends : A Data Overview with Python
By: Sarang Manjrekar
Tags: ESPN, Visualization, Cricket, Matplotlib, Python

Game of Cricket was brought to India by the British and today it’s the most followed game in the subcontinent. The game of cricket is 150 Years old and as any other game, it has evolved thorugh the ages to become one of the most followed modern sport today.

The game earlier used to be the sport of the Elite and hence called the Gentleman’s game. Today we have fascinating stories of cricketers like MS Dhoni, a Wicketkeeper Captain hailing from a Tier II city like Ranchi, T.Natarajan who rose onto the Horizon from even more humble background, and so are numerous stories of small town boys coming to Centre stage and grabbing attention of cricket crazy nation and truning into superstars.

Even with so much of a changing landscpae, cricket is still a game played on a 22-yard pitch, with 2 teams of 11 players each, contesting to outsmart the other in various facets of the game namely Batting, Bowling and Fielding.

Test Cricket is unarguably considered to be the purest and most challenging format of the game by players and critics alike, worldwide.

History of this game takes us back to 1877, when the first Test match was played between England and Australia at the famous Melbourne Cricket Ground.

As the saying goes : “Numbers dont lie”. Scorecard of a played game of cricket provides a fair enough glimpse into any match. Hence I took to scrap the data from ESPNCricinfo which happens to be One stop resource for scorecards of all the matches played till date.

Web scrapping the data, I’ve created a Match detail master dataset, comprising of data for over 2400 Test matches played in last 150 years of Test cricket.

We’ll be exploring trends towards various facets of this multidisciplinary game.

Test Match: Most Challenging Format of the Game

Starting with Web scrapping from ESPNCricinfo Website :

I’ve written Python functions to scrap data at primarily 3 levels :

Get CricInfo Match IDs of all the test matches Get relevant scorecard data features for each Test Match Transform the extracted features to build meaningful features

Themes to Explore in the Dataset :

I.A - Spread of the game to Indian SubContinent

When Cricket was born in 19th century, the Subcontinent was very much under foreign rule and even though the oldest stadium in India “The Eden Gardens” of Kolkata was built in 1864, the first match here was held only in 1934.

Until early 1900s, Only England, Australia, South Africa were the prominent countries where professional cricket was played at the highest level.British colonies in Asia were gaining independence around the mid 20th century and also were finding an identity of their own at the world stage, be it in political sphere or the sporting one.
Basics of Donut charts with Python’s Matplotlib
By: Thiago Carvalho
Tags: Donut Chart, Data Visualization, Donuts, Matplotlib, Python

Pies

There’s no method for drawing a donut chart in Matplotlib, but we can quickly transform a Pie chart with wedgeprops.

Let’s start with a simple pie.

import matplotlib.pyplot as plt plt.pie([87,13], startangle=90, colors=['#5DADE2', '#515A5A']) plt.show()

Pie — Image by the author

Now we can add the parameter wedgeprops and define the width of the edges, where one means the border will go all the way to the center.

fig, ax = plt.subplots(figsize=(6, 6))



ax.pie([87,13],

wedgeprops={'width':0.3},

startangle=90,

colors=['#5DADE2', '#515A5A']) plt.show()

Donut — Image by the author

That’s very straightforward. And now that we can use the space at the center to make our data even more evident.

fig, ax = plt.subplots(figsize=(6, 6)) wedgeprops = {'width':0.3, 'edgecolor':'black', 'linewidth':3} ax.pie([87,13], wedgeprops=wedgeprops, startangle=90, colors=['#5DADE2', '#515A5A']) plt.title('Worldwide Access to Electricity', fontsize=24, loc='left') plt.text(0, 0, "87%", ha='center', va='center', fontsize=42)

plt.text(-1.2, -1.2, "Source: ourworldindata.org/energy-access", ha='left', va='center', fontsize=12) plt.show()

Donut chart with details — Image by the author

Donut charts are specifically helpful when we have a simple comparison or proportion to display. In my opinion, the best way to use them is like a circular progress bar, such as the example where we have a single proportion to highlight.

In these cases, we can simplify the chart even more.

fig, ax = plt.subplots(figsize=(6, 6)) data = [87, 13]

wedgeprops = {'width':0.3, 'edgecolor':'black', 'lw':3}

patches, _ = ax.pie(data, wedgeprops=wedgeprops, startangle=90, colors=['#5DADE2', 'white']) patches[1].set_zorder(0)

patches[1].set_edgecolor('white') plt.title('Worldwide Access to Electricity', fontsize=24, loc='left')

plt.text(0, 0, f"{data[0]}%", ha='center', va='center', fontsize=42)

plt.text(-1.2, -1.3, "Source: ourworldindata.org/energy-access", ha='left', va='top', fontsize=12) plt.show()
MEET MY RAHUL!
By: Sneha Agrawal
Tags: Non Fiction, Life Lessons, Real Life Stories, Positivity, Life

MEET MY RAHUL!

I met one Rahul today .

Big universities, access to best learning resources, guidance by the best teachers and mentors — so many people must be dreaming about such an education and yet a very small part of the world gets even the basic minimum education.

But is there any university that can teach better than life itself ?

After all, life is the greatest teacher and time is it’s strongest weapon. World is full of such examples of great people who could challenge their circumstances and rise despite coming from humble background.

When a tigress gives birth to a cub, he has to learn to fight for his survival.

Rahul was that one cub.

At the innocent age of 12, when kids ask their parents to buy them toys, Rahul was selling books to help his mother run the household.

He still managed to maintain a broad and the purest smile on his face. A smile that was contagious.

While I was everyday complaining about my job, relations, body, friends and foes, Rahul came as a breeze of fresh and cool air. My mind immediately asked me how was he so happy amidst so many adversities. Happiness is a choice, I now knew. I instantly forgot all my worries.

An hour spent with him had filled me with so much energy that was going to last with me for a very very long time, I was sure.

It was an evening well spent :)

Thanks Rahul for oozing out so much positivity, a raw and unadulterated innocence.

This world needs so much more of it.

I want to meet many more Rahul in future..

If you know someone in your vicinity, I would love to cover the story of that Rahul..

It is my way of uplifting the spirits of people around me by sharing these real life stories..

This post was originally posted on The phoenix Girl’s blog at https://thephoenixgirl86.blogspot.com/