Special Data Types

Back

Loading concept...

🎨 Matplotlib’s Special Data Types: Your Chart’s Secret Superpowers!

Imagine you’re a museum curator. You have three special rooms: one shows when things happened (dates), one groups items by category (like “paintings” vs “sculptures”), and one displays summary tables. Matplotlib gives you these same three superpowers for your charts!


🗓️ Date Axis Handling: Time Travel for Your Charts

What is Date Axis Handling?

Think of it like a calendar on your wall. When you want to show things that happened over time—like how many cookies you ate each day—you need dates on your chart. Matplotlib knows how to read calendars!

The Magic Behind Dates

Matplotlib has a special helper called matplotlib.dates (we call it mdates). It’s like a translator that turns calendar dates into positions on your chart.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

# Your diary of cookie eating
dates = [
    datetime(2024, 1, 1),
    datetime(2024, 1, 15),
    datetime(2024, 2, 1)
]
cookies = [5, 8, 3]

fig, ax = plt.subplots()
ax.plot(dates, cookies)

# Tell the chart how to show dates
ax.xaxis.set_major_formatter(
    mdates.DateFormatter('%b %d')
)
plt.show()

Date Formatters: Speaking Calendar Language

Code What It Shows Example
%Y Full year 2024
%m Month number 01
%b Month name Jan
%d Day 15

Locators: Where to Put the Tick Marks

Locators decide WHERE to put marks on your date axis. Like putting stickers on every Monday!

# Show a mark for every month
ax.xaxis.set_major_locator(
    mdates.MonthLocator()
)

# Show a mark for every week
ax.xaxis.set_major_locator(
    mdates.WeekdayLocator(byweekday=0)
)
graph TD A["Your Dates"] --> B["DateFormatter"] B --> C["Pretty Labels"] A --> D["Locator"] D --> E["Where Ticks Go"] C --> F["Beautiful Timeline!"] E --> F

Pro Tip: Auto-Rotate Labels

Dates can be long. Use this magic spell:

fig.autofmt_xdate()

This tilts your date labels so they don’t overlap!


📊 Categorical Data Plotting: Sorting Things Into Boxes

What is Categorical Data?

Imagine sorting your toys into boxes: Cars, Dolls, Blocks. These are categories—not numbers! Matplotlib can put these word-labels on your chart.

Bar Charts with Categories

The most natural home for categories is a bar chart:

import matplotlib.pyplot as plt

fruits = ['Apple', 'Banana', 'Cherry']
sales = [45, 30, 55]

plt.bar(fruits, sales)
plt.xlabel('Fruit Type')
plt.ylabel('Sales')
plt.show()

That’s it! Matplotlib sees words and automatically spaces them out.

Horizontal Bar Charts

Sometimes categories have long names. Flip it sideways!

animals = [
    'Elephant',
    'Giraffe',
    'Hippopotamus'
]
weights = [5000, 1200, 1500]

plt.barh(animals, weights)
plt.xlabel('Weight (kg)')
plt.show()

Scatter Plots with Categories

Yes, you can scatter dots on category axes too!

teams = ['Red', 'Blue', 'Red', 'Green']
scores = [85, 92, 78, 88]

plt.scatter(teams, scores)
plt.show()

Ordering Your Categories

By default, categories appear in the order you gave them. Want alphabetical?

categories = ['Zebra', 'Apple', 'Mango']
values = [10, 20, 15]

# Sort them yourself
sorted_pairs = sorted(
    zip(categories, values)
)
sorted_cats, sorted_vals = zip(
    *sorted_pairs
)

plt.bar(sorted_cats, sorted_vals)
plt.show()
graph TD A["Word Labels"] --> B["Matplotlib"] B --> C["Evenly Spaced Positions"] C --> D["Category Axis"] D --> E["Clear Comparisons!"]

đź“‹ Tables in Plots: Data Meets Art

What Are Tables in Plots?

Sometimes you want to show exact numbers right inside your chart. Like putting a little report card next to your drawing!

The plt.table() Function

import matplotlib.pyplot as plt

# Your data
data = [
    ['Mon', 10, 8],
    ['Tue', 15, 12],
    ['Wed', 7, 9]
]

columns = ['Day', 'Sales', 'Returns']

fig, ax = plt.subplots()
ax.axis('off')  # Hide the chart axes

table = ax.table(
    cellText=data,
    colLabels=columns,
    loc='center'
)

plt.show()

Table + Chart Combo

The real magic is combining a chart WITH a table:

import matplotlib.pyplot as plt

days = ['Mon', 'Tue', 'Wed']
sales = [10, 15, 7]

fig, ax = plt.subplots()

# Draw the bar chart
ax.bar(days, sales)

# Add a table below
table_data = [[str(s) for s in sales]]
table = ax.table(
    cellText=table_data,
    rowLabels=['Sales'],
    colLabels=days,
    loc='bottom',
    cellLoc='center'
)

# Make room for the table
plt.subplots_adjust(bottom=0.2)
plt.show()

Styling Your Table

Make it pretty!

table = ax.table(
    cellText=data,
    colLabels=columns,
    loc='center',
    cellLoc='center'
)

# Make header row special
table.auto_set_font_size(False)
table.set_fontsize(10)
table.scale(1.2, 1.5)

# Color the header
for i in range(len(columns)):
    table[(0, i)].set_facecolor('#4CAF50')
    table[(0, i)].set_text_props(
        color='white'
    )

Table Location Options

loc Value Where It Goes
'top' Above the plot
'bottom' Below the plot
'center' Middle (no chart)
'left' Left side
'right' Right side
graph TD A["Your Data Array"] --> B["plt.table"] B --> C["cellText: Values"] B --> D["colLabels: Headers"] B --> E["loc: Position"] C --> F["Beautiful Table!"] D --> F E --> F

🎯 Quick Summary

Feature What It Does Key Function
Date Axis Shows time on axis mdates.DateFormatter()
Categories Shows word labels Just pass strings!
Tables Shows data grid ax.table()

🚀 Your Mission

You now have three superpowers:

  1. Time Travel – Put dates on any axis
  2. Word Magic – Use categories instead of numbers
  3. Data Display – Add tables right inside charts

Mix and match them! A bar chart with categories, dates on x-axis, and a summary table below? You can do that now!

Remember: Charts tell stories. Dates show WHEN, categories show WHAT, and tables show EXACTLY how much. Together, they make your data story complete! ✨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.