Other charts

admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Other charts

Post by admin »

Got it, Ramajayam. Here’s a clean, paste-ready phpBB post with BBCode. It includes both Matplotlib and Seaborn versions of the same scatter plot (y = x²). I’ve kept it minimal and classroom-friendly.

\Python: Scatter Plot (y = x²) — Matplotlib & Seaborn\

\What you’ll learn:\ how to plot a simple scatter chart, label axes, and set a title.
\Tip:\ Run either block as-is; they’re independent.

\A) Using Matplotlib\
\

Code: Select all


# Scatter plot: y = x^2 (Matplotlib)

import matplotlib.pyplot as plt

x = [1,2,3,4,5,6,7,8,9]
y = [1,4,9,16,25,36,49,64,81]

plt.scatter(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('X vs Y')
plt.show()
\B) Using Seaborn\

Code: Select all


# Scatter plot: y = x^2 (Seaborn)

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

x = np.array([1,2,3,4,5,6,7,8,9])
y = np.array([1,4,9,16,25,36,49,64,81])

df = pd.DataFrame({'X': x, 'Y': y})
sns.scatterplot(x='X', y='Y', data=df)

plt.xlabel('X')
plt.ylabel('Y')
plt.title('X vs Y')
plt.show()
\Quick checks (be skeptical):\
\
  • \
  • Do points rise smoothly? (Yes—positive correlation.)
    \
  • Does changing X change Y predictably? (Yes—quadratic growth.)
    \[\*]Forward-looking tweak: try non-linear fits or log scales when Y grows fast.
    \
If you want this styled for your ICAI module (headings, numbered steps, or Q\&A under the code), say the word and I’ll refactor it.
admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Python: Histograms

Post by admin »

Python: Histograms

To visualize the frequency distribution of continuous variables, histograms are utilized.
The histogram's length and width represent frequency and interval respectively.
You must divide the interval into non-overlapping bins to construct a histogram.

Bin size plays an important role:
- Too small → bins will have almost the same frequency.
- Too large → all values will be included in very few bins, leading to poor insights.

Example using Matplotlib:

Code: Select all

# Plotting function y = x^2
import matplotlib.pyplot as plt

y = [1,5,6,9,15,25,36,95,86,84,25,35,68,
     65,41,75,89,94,55,96,85,35,25,14,53,97,62,35]

plt.hist(y, color='blue')
plt.show()
Example using Seaborn:

Code: Select all

# Plotting function y = x^2
import seaborn as sns

y = [1,5,6,9,15,25,36,95,86,84,25,35,68,
     65,41,75,89,94,55,96,85,35,25,14,53,97,62,35]

sns.histplot(y, bins=10, color='green')
plt.show()
admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Python: Histograms

Post by admin »

Python: Histograms

Histograms visualize the frequency distribution of continuous variables.
- Length → frequency
- Width → interval range (bin size)
Too small bins → almost equal frequencies.
Too large bins → very few bins, less insight.

Matplotlib Example:

Code: Select all

# Plotting function y = x^2
import matplotlib.pyplot as plt

y = [1,5,6,9,15,25,36,95,86,84,25,35,68,
     65,41,75,89,94,55,96,85,35,25,14,53,97,62,35]

plt.hist(y, color='blue')
plt.show()
Seaborn Example:

Code: Select all

# Plotting function y = x^2
import seaborn as sns
import matplotlib.pyplot as plt

y = [1,5,6,9,15,25,36,95,86,84,25,35,68,
     65,41,75,89,94,55,96,85,35,25,14,53,97,62,35]

sns.histplot(y, bins=10, color='green')
plt.show()
---

Python: Bar Plots

Bar plots compare quantities across categories.
Example: Comparing wages of two types of workers over days.

Matplotlib Example:

Code: Select all

import matplotlib.pyplot as plt

plt.figure(figsize=(6,3.5))
plt.bar([0.25,2.25,3.25,5.25,7.25],[300,400,200,600,700],
        label="Carpenter",color='b',width=0.5)
plt.bar([0.75,1.75,2.75,3.75,4.75],[50,30,20,50,60],
        label="Plumber", color='g',width=0.5)

plt.legend()
plt.xlabel('Days')
plt.ylabel('Wage')
plt.title('Details')
plt.show()
Seaborn Example:

Code: Select all

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df1 = pd.DataFrame({
    'Days':[0.25,2.25,3.25,5.25,7.25],
    'No. of workers':[300,400,200,600,700],
    'Type of workers':'Carpenter'
})

df2 = pd.DataFrame({
    'Days':[0.75,1.75,2.75,3.75,4.75],
    'No. of workers':[50,30,20,50,60],
    'Type of workers':'Plumber'
})

df3 = pd.concat([df1,df2])
plt.figure(figsize=(4.2,2.5))
sns.barplot(x='Days',y='No. of workers',data=df3,hue='Type of workers',palette='Blues')
plt.show()
admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Python: Box Plots

Post by admin »

Python: Box Plots

A Box Plot (or Whisker Plot) is used to visualize the distribution of data and identify outliers.
Key components:
- Median – Middle value of the dataset
- Q1 – 25th percentile
- Q3 – 75th percentile
- IQR – Interquartile Range (Q3 – Q1)
- Outliers – Points lying beyond 1.5 × IQR from the quartiles

---

Matplotlib Example:

Code: Select all

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(10)
data = np.random.normal(100, 20, 200)

plt.figure(figsize=(6,3.5))
plt.boxplot(data, vert=False)
plt.show()
Seaborn Example:

Code: Select all

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(10)
data = np.random.normal(100, 20, 200)

plt.figure(figsize=(4,2.5))
sns.boxplot(data, orient='h')
plt.show()
admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Heat Maps

Post by admin »

Code: Select all

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

Temperature = np.array([
    15,26,32,35,45,12,19,24,26,39,37,29,     # 2019
    15,16,17,18,19,20,20,20,20,20,20,20,     # 2020
    25,30,35,40,45,50,50,50,50,50,50,50,     # 2021
    30,35,40,45,50,55,60,65,70,75,35,40      # 2022
]).reshape(4,12)

months = ["January", "February", "March", "April", "May", "June", "July",
          "August", "September", "October", "November", "December"]

year = [2019, 2020, 2021, 2022]

df5 = pd.DataFrame(data=Temperature, columns=months, index=year)

plt.figure(figsize=(8,3))
sns.heatmap(df5, annot=True, cmap='crest')
plt.show()
admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Python: Pair Plots

Post by admin »

Python: Pair Plots

A Pair Plot visualizes pairwise relationships in a dataset.
- Each variable is plotted on both the X and Y axes against all other variables.
- Diagonal plots show univariate distributions (histograms or KDE plots).
- Useful for spotting correlations and clustering patterns.

Example using Seaborn’s built-in "tips" dataset:

Code: Select all

import seaborn as sns
import matplotlib.pyplot as plt

# Load dataset
df = sns.load_dataset('tips')

# Create Pair Plot
plt.figure(figsize=(5,3.5))
sns.pairplot(df, hue='sex')
plt.show()
Cell In[29], line 8
Example using Seaborn’s built-in "tips" dataset:
^
SyntaxError: invalid character '’' (U+2019)
admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Re: Other charts

Post by admin »

Python: Count Plot

A Count Plot shows the frequency of each category in a dataset.
Useful for categorical data visualization.

Example – Count of male and female in the 'tips' dataset:

Code: Select all

import seaborn as sns
import matplotlib.pyplot as plt

plt.figure(figsize=(4,2.5))
df = sns.load_dataset('tips')
sns.countplot(x='sex', data=df, palette='Blues')
plt.show()
admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Re: Other charts

Post by admin »

Python: Sunburst Chart

A Sunburst chart is useful for representing hierarchical data.
It displays categories and subcategories in concentric rings.

Example – Total bill amounts grouped by day and sex:

Code: Select all

import plotly.express as px

df = px.data.tips()
px.sunburst(df, path=['day', 'sex'], values='total_bill').show()
admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Re: Other charts

Post by admin »

Python: Waterfall Chart

A Waterfall Chart is useful for visualizing cumulative effects of sequential values —
e.g., starting value, increases, decreases, and the resulting total.

Example – Profit and Loss Statement using Plotly:

Code: Select all

import plotly.graph_objects as go

fig = go.Figure(go.Waterfall(
    x = [["2016", "2017", "2017", "2017", "2018", "2018", "2018", "2018"],
         ["initial", "q1", "q2", "q3", "total", "q1", "q2", "q3", "total"]],
    measure = ["absolute", "relative", "relative", "relative", "total",
               "relative", "relative", "relative", "total"],
    y = [10, 20, 30, -10, None, 10, 20, -40, None],
    base = 300,
    decreasing = {"marker": {"color": "red", "line": {"color": "red", "width": 2}}},
    increasing = {"marker": {"color": "green"}},
    totals = {"marker": {"color": "deep sky blue", "line": {"color": "blue", "width": 3}}}
))

fig.update_layout(title = "Profit and loss statement", waterfallgap = 0.3)
fig.show()
admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Re: Other charts

Post by admin »

Code: Select all

import matplotlib.pyplot as plt

Employee = ['Roshni', 'Shyam', 'Priyanshi', 'Harshit', 'Anmol']
Salary = [40000, 50000, 70000, 54000, 44000]

# Fixed last color: '#A2222F' (valid hex)
colors = ['#9999FF', '#0066FF', '#7777FF', '#5555FF', '#A2222F']
explode = (0.05, 0.05, 0.05, 0.05, 0.05)

# Create Pie Chart
plt.pie(Salary, colors=colors, labels=Employee,
        autopct="%1.1f%%", pctdistance=0.85, explode=explode)

# Draw center circle to make it a donut chart
centre_circle = plt.Circle((0, 0), 0.70, fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

plt.show()
Post Reply