Home>

I am addicted to using matplotlib with python.
I'm not familiar with using matplotlib, but can you tell me what caused the following behavior?
By the way, we confirm in google colabo environment.

## Import library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
% matplotlib inline
## Create two data frames: the only difference is the type of index
df1 = pd.DataFrame ([[970, 975, 975],
                    [1010, 1020, 985],
                    [1015, 1002, 995],
                    [1008, 1035, 999]],
                    index = [2013, 2014, 2015, 2016], columns = ['Toyota', 'VW', 'GM'])
year1 = df1.index.values.astype (int)
print (year1)
df1

"" "Result
[2013 2014 2015 2016]
        Toyota VW GM
2013 970 975 975
2014 1010 1020 985
2015 1015 1002 995
2016 1008 1035 999
"" "

df2 = pd.DataFrame ([[970, 975, 975],
                    [1010, 1020, 985],
                    [1015, 1002, 995],
                    [1008, 1035, 999]],
                    index = ['2013', '2014', '2015', '2016'], columns = ['Toyota', 'VW', 'GM'])
year2 = df2.index.values.astype (int)
print (year2)
df2

"" "Result
[2013 2014 2015 2016]
Toyota VW GM
2013 970 975 975
2014 1010 1020 985
2015 1015 1002 995
2016 1008 1035 999
"" "
## Drawing with plot makes it strange. I do not know the cause.
fig, ax1 = plt.subplots ()
df1.plot (ax = ax1)
ax1.set (xlim = (year1.min (), year1.max ()))

Result of df1:

fig, ax2 = plt.subplots ()
df2.plot (ax = ax2)
ax2.set (xlim = (year2.min (), year2.max ()))

The result of df2:

If anyone can understand the cause of this difference in behavior, please let me know.

  • Answer # 1

    df1specifies the numerical value asindex = [2013, 2014, 2015, 2016], so the position of the x point on the line graph is 2013, 2014, 2015, 2016
    On the other hand,df2is specified asindex = ['2013', '2014', '2015', '2016']The position of the x point is 0, 1, 2, 3 (if the x-axis value is a string, the point position defaults to 0, 1, ...).

    Despite this,ax2.set (xlim = (2013, 2016))is specified, so the area outside the line is displayed, and as a result, a graph with nothing is drawn. It has been.

    If you delete

    ax2.set (xlim = (year2.min (), year2.max ())), the graph will be displayed correctly.

  • Answer # 2

    I may have resolved myself, so I will add it.
    When doing DataFrame.plot (), is the cause that the x-axis type has become a string type in the case of df2?

    ## In df2.plot (), is the x axis the object type axis?
    ## Make index type int
    df2.index = df2.index.astype (int)
    fig, ax2 = plt.subplots ()
    df2.plot (ax = ax2)
    ax2.set (xlim = (year2.min (), year2.max ()))

    In this code execution, the graph was drawn as expected.