There are two common ways to plot the values in a pandas Series:
Method 1: Create Line Plot from pandas Series
import pandas as pd import matplotlib.pyplot as plt plt.plot(my_series.index, my_series.values)
Method 2: Create Histogram from pandas Series
import pandas as pd import matplotlib.pyplot as plt my_series.plot(kind='hist')
The following examples show how to use each method in practice.
Example 1: Create Line Plot from pandas Series
The following code shows how to create a line plot from a pandas Series:
import pandas as pd import matplotlib.pyplot as plt #create pandas Series my_series = pd.Series([2, 2, 2, 3, 3, 4, 5, 7, 8, 9, 12, 12, 14, 15, 16, 16, 18, 19, 22, 22, 22, 25, 26, 27, 30, 33, 33, 33, 34, 35]) #create line plot to visualize values in Series plt.plot(my_series.index, my_series.values)
The x-axis shows the index values of the pandas Series and the y-axis shows the actual values in the Series.
You can also use various functions from pandas and matplotlib to customize the appearance of the line as well as the axis labels and title of the plot:
#create customized line plot plt.plot(my_series.index, my_series.values, color='red', linewidth=2.5) #add axis labels and title plt.xlabel('Index') plt.ylabel('Values') plt.title('Line Plot of Pandas Series')
Example 2: Create Histogram from pandas Series
The following code shows how to create a histogram from a pandas Series:
import pandas as pd import matplotlib.pyplot as plt #create pandas Series my_series = pd.Series([2, 2, 2, 3, 3, 4, 5, 7, 8, 9, 12, 12, 14, 15, 16, 16, 18, 19, 22, 22, 22, 25, 26, 27, 30, 33, 33, 33, 34, 35]) #create histogram visualize distribution of values in Series my_series.plot(kind='hist')
The x-axis shows the values of the pandas Series and the y-axis shows the frequency of the values.
You can also use various functions from pandas and matplotlib to customize the appearance of the histogram as well as the number of bins used in the histogram:
#create histogram with 15 bins my_series.plot(kind='hist', edgecolor='black', color='gold', bins=15) #add axis labels and title plt.xlabel('Values') plt.title('Histogram of Pandas Series')
Note that the default number of bins used in a histogram is 10.
Feel free to use the bins argument to increase this number to produce more bins or reduce this number to produce fewer bins.
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
How to Filter Pandas Series by Value
How to Convert Pandas Series to DataFrame
How to Convert Pandas Series to NumPy Array