Plot 3 Different Metrics in One Figure
Description:
This script uses matplotlib
to plot Sales, Revenue, and Units Sold over a 7-day period on one chart. Each metric is shown with a unique marker and color, and the dates are rotated for better visibility.
Code Explanation:
-
df
contains your data: dates, sales numbers, revenue, and units sold. -
plt.plot()
draws a separate line for each metric.-
marker='o'
,'s'
, and'^'
show dots, squares, and triangles for each line. -
Different colors help tell the lines apart.
-
-
plt.xticks(rotation=45)
rotates the date labels so they don’t overlap. -
plt.legend()
adds a key to explain which line is which. -
plt.tight_layout()
automatically adjusts spacing to prevent text from getting cut off. -
Finally,
plt.show()
displays the chart.
Program:
import matplotlib.pyplot as plt
import pandas as pd
# Sample data
data = {
'Date': pd.date_range(start='2024-01-01', periods=7, freq='D'),
'Sales': [100, 120, 90, 140, 160, 130, 150],
'Revenue': [1000, 1500, 1200, 1800, 2000, 1700, 1900],
'Units': [10, 12, 9, 14, 16, 13, 15]
}
df = pd.DataFrame(data)
# Plotting all three metrics
plt.figure(figsize=(10, 6))
plt.plot(df['Date'], df['Sales'], marker='o', label='Sales', color='blue')
plt.plot(df['Date'], df['Revenue'], marker='s', label='Revenue', color='green')
plt.plot(df['Date'], df['Units'], marker='^', label='Units Sold', color='red')
# Formatting
plt.title('Sales, Revenue, and Units Over Time')
plt.xlabel('Date')
plt.ylabel('Values')
plt.xticks(rotation=45) # Corrected line
plt.grid(True)
plt.legend()
plt.tight_layout()
# Show the plot
plt.show()
Output: