Filter Data Before Plotting
Code Description:
This code filters and plots the sales data, displaying only the days where sales are greater than 100. The filtered data is then visualized as a line chart.
Code Explanation:
-
Data Preparation:
-
The
data
dictionary is created with dates and sales values for 10 days. -
A pandas
DataFrame
is created from the dictionary.
-
-
Data Filtering:
-
The filter condition
df['Sales'] > 100
is applied, which keeps only the rows where the sales are greater than 100. This is stored infiltered_df
.
-
-
Plotting:
-
A line plot is drawn using the filtered data (
filtered_df['Date']
andfiltered_df['Sales']
). -
marker='o'
is used to display markers at each data point, andcolor='green'
sets the line color to green. -
plt.xticks(rotation=45)
rotates the x-axis labels for better readability. -
The chart includes a title, axis labels, grid, and a legend for clarity.
-
-
Displaying the Plot:
-
plt.show()
displays the final plot with the filtered data.
-
Program:
import matplotlib.pyplot as plt
import pandas as pd
# Sample data
data = {
'Date': pd.date_range(start='2024-01-01', periods=10, freq='D'),
'Sales': [80, 120, 90, 150, 200, 60, 180, 110, 95, 130]
}
df = pd.DataFrame(data)
# Filter data: only show days with sales > 100
filtered_df = df[df['Sales'] > 100]
# Plot the filtered data
plt.figure(figsize=(8, 5))
plt.plot(filtered_df['Date'], filtered_df['Sales'], marker='o', color='green', label='Sales > 100')
plt.title('Filtered Sales (Only Sales > 100)')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.xticks(rotation=45)
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
Output: