Python Data Visualization

Introduction

Data visualization turns numbers into charts, graphs, and visuals. Python has powerful libraries like matplotlib, seaborn, and plotly for this job. In this tutorial, you’ll learn the essentials of plotting data in Python.

1. Installing Libraries

pip install matplotlib seaborn
    

2. Basic Line Plot

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 22, 30]

plt.plot(x, y)
plt.title("Line Chart")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.show()
    

3. Bar Chart

plt.bar(["A", "B", "C"], [5, 12, 9])
plt.title("Bar Chart Example")
plt.show()
    

4. Scatter Plot

plt.scatter([1, 2, 3], [2, 5, 1])
plt.title("Scatter Plot")
plt.show()
    

5. Histogram

data = [1,2,2,3,3,3,4,4,5,5,5,5]
plt.hist(data)
plt.title("Histogram")
plt.show()
    

6. Seaborn Styling

import seaborn as sns

sns.set(style="darkgrid")
sns.lineplot(x=[1,2,3], y=[5,10,7])
plt.show()
    

7. Multiple Plots in One Figure

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

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

plt.show()
    

8. Pie Chart

sizes = [40, 30, 20, 10]
labels = ["A", "B", "C", "D"]

plt.pie(sizes, labels=labels, autopct="%1.1f%%")
plt.title("Pie Chart Example")
plt.show()
    

9. Saving Charts to File

plt.savefig("chart.png")
    

10. pandas + Plotting

import pandas as pd

df = pd.DataFrame({
    "year": [2020, 2021, 2022],
    "sales": [100, 150, 200]
})

df.plot(x="year", y="sales", kind="line")
plt.show()
    

Summary