Failed to convert value(s) to axis units

The error “failed to convert value(s) to axis units” typically occurs when you are trying to plot values on an axis that cannot be converted to the required units of the axis. This error is commonly encountered while using plotting libraries like Matplotlib in Python.

Let’s consider an example to understand this error better. Suppose you have a dataset with two columns: “Age” and “Income”. You want to create a scatter plot to visualize the relationship between age and income. Here’s a sample code:

  
    import matplotlib.pyplot as plt
    
    # Sample data
    age = [25, 30, 35, 40, "45", 50]
    income = [30000, 40000, 50000, 60000, 70000, 80000]
    
    # Create scatter plot
    plt.scatter(age, income)
    plt.xlabel('Age')
    plt.ylabel('Income')
    plt.show()
  
  

In this example, notice that the fifth value in the “Age” column is provided as a string (“45”) instead of an integer. Trying to plot this string value as an age on the x-axis will result in a “failed to convert value(s) to axis units” error. To overcome this error, you need to ensure that all the values in the “Age” column are of the same data type, preferably a numeric type like integers.

To fix the error in the example above, you can modify the code as follows:

  
    import matplotlib.pyplot as plt
    
    # Sample data
    age = [25, 30, 35, 40, 45, 50]
    income = [30000, 40000, 50000, 60000, 70000, 80000]
    
    # Create scatter plot
    plt.scatter(age, income)
    plt.xlabel('Age')
    plt.ylabel('Income')
    plt.show()
  
  

After ensuring that all the values in the “Age” column are numeric, the scatter plot will be created successfully without any conversion errors.

Read more interesting post