Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to plot certain rows of a Pandas dataframe using Matplotlib?
To plot certain rows of a Pandas DataFrame, you can use iloc[] to slice specific rows and then apply the plot() method. This is useful when you want to visualize only a subset of your data.
Setting Up the Environment
First, let's import the necessary libraries and create a sample DataFrame ?
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Set figure size for better visualization
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
# Create a DataFrame with random data
np.random.seed(42) # For reproducible results
df = pd.DataFrame(np.random.randn(10, 5), columns=list('abcde'))
print("Full DataFrame:")
print(df)
Full DataFrame:
a b c d e
0 0.496714 -0.138264 0.647689 1.523030 -0.234153
1 -0.234137 1.579213 0.767435 -0.469474 0.542560
2 0.241962 -1.913280 -1.724918 -0.562288 -1.012831
3 0.314247 -0.908024 -1.412304 0.067528 -0.943725
4 0.896775 -0.601763 1.484537 -0.013497 1.761260
5 -0.845206 -1.478522 -0.635846 -1.469645 0.154947
6 -1.337070 0.844622 -0.743234 0.319039 -0.879236
7 0.195222 1.006757 0.458346 -1.207814 -1.424065
8 0.156349 0.230794 0.533601 0.967297 2.236161
9 -0.720589 0.298238 -1.203666 0.539249 -1.186896
Plotting Specific Rows
Now let's plot only the first 6 rows using iloc[] slicing ?
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
# Create DataFrame
np.random.seed(42)
df = pd.DataFrame(np.random.randn(10, 5), columns=list('abcde'))
# Plot only first 6 rows
df.iloc[0:6].plot(y='e', marker='o', linewidth=2, markersize=8)
plt.title('Plot of Column "e" for First 6 Rows')
plt.xlabel('Row Index')
plt.ylabel('Values')
plt.grid(True, alpha=0.3)
plt.show()
print("Data being plotted (first 6 rows):")
print(df.iloc[0:6])
Data being plotted (first 6 rows):
a b c d e
0 0.496714 -0.138264 0.647689 1.523030 -0.234153
1 -0.234137 1.579213 0.767435 -0.469474 0.542560
2 0.241962 -1.913280 -1.724918 -0.562288 -1.012831
3 0.314247 -0.908024 -1.412304 0.067528 -0.943725
4 0.896775 -0.601763 1.484537 -0.013497 1.761260
5 -0.845206 -1.478522 -0.635846 -1.469645 0.154947
Plotting Multiple Columns from Specific Rows
You can also plot multiple columns from the selected rows ?
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
plt.rcParams["figure.figsize"] = [10, 6]
np.random.seed(42)
df = pd.DataFrame(np.random.randn(10, 5), columns=list('abcde'))
# Plot multiple columns for rows 2 to 8
df.iloc[2:8][['c', 'd', 'e']].plot(kind='line', marker='o', linewidth=2)
plt.title('Multiple Columns Plot for Rows 2-7')
plt.xlabel('Row Index')
plt.ylabel('Values')
plt.legend(title='Columns')
plt.grid(True, alpha=0.3)
plt.show()
Different Row Selection Methods
Here are various ways to select and plot specific rows ?
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(42)
df = pd.DataFrame(np.random.randn(10, 5), columns=list('abcde'))
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
# Method 1: First n rows
df.iloc[:4].plot(y='a', ax=axes[0,0], title='First 4 rows', marker='o')
# Method 2: Last n rows
df.iloc[-4:].plot(y='b', ax=axes[0,1], title='Last 4 rows', marker='s')
# Method 3: Specific row range
df.iloc[3:7].plot(y='c', ax=axes[1,0], title='Rows 3-6', marker='^')
# Method 4: Non-consecutive rows
df.iloc[[0, 2, 4, 6]].plot(y='d', ax=axes[1,1], title='Even-indexed rows', marker='D')
plt.tight_layout()
plt.show()
Key Points
-
iloc[start:end]selects rows from start to end-1 -
iloc[:n]selects the first n rows -
iloc[-n:]selects the last n rows -
iloc[[0,2,4]]selects specific non-consecutive rows - Use
plot(y='column_name')to plot a specific column
Conclusion
Use iloc[] with slicing to select specific rows from a DataFrame, then apply plot() to visualize the data. This approach is perfect for analyzing subsets of your data or creating focused visualizations from large datasets.
Advertisements
