matplotlib axis values are not sorted
The values are treated as strings. Convert them to float using:
val = float(val)
xlabel and ylabel values are not sorted in matplotlib scatterplot
- The issue is that the values are
string
type, so they are plotted in the order given in the list, not in numeric order. - The values must have the symbols removed from the end, and then converted to a numeric type.
Add-on to existing code using csv
module
- Given the existing code, it would be easy to
map()
the values in the lists to afloat
type.
indexes = [i.split('%', 1)[0] for i in index]
dividend_yield = [d.split('%', 1)[0] for d in dividend]
pe_ratio = [p.split('X', 1)[0] for p in pe]
# add mapping values to floats after removing the symbols from the values
indexes = list(map(float, indexes))
dividend_yield = list(map(float, dividend_yield))
pe_ratio = list(map(float, pe_ratio))
# plot
x = dividend_yield[:5]
y = pe_ratio[:5]
plt.scatter(x, y, label='Healthcare P/E & Dividend', alpha=0.5)
plt.xlabel('Dividend yield')
plt.ylabel('Pe ratio')
plt.legend(bbox_to_anchor=(1, 1), loc='upper left')
plt.show()
Using pandas
- Remove the symbol from the end of the strings in the columns with
col.str[:-1]
- Convert the columns to
float
type with.astype(float)
- Using
pandas v1.2.4
andmatplotlib v3.3.4
- This option reduces the required code from 23 lines to 4 lines.
import pandas as pd
# read the file
df = pd.read_csv('xlv_xlu_combined_td.csv')
# remove the symbols from the end of the number and set the columns to float type
df.iloc[:, 1:] = df.iloc[:, 1:].apply(lambda col: col.str[:-1]).astype(float)
# plot the first five rows of the two columns
ax = df.iloc[:5, 2:].plot(x='dividend', y='pe', kind='scatter', alpha=0.5,
ylabel='Dividend yield', xlabel='Pe ratio',
label='Healthcare P/E & Dividend')
ax.legend(bbox_to_anchor=(1, 1), loc='upper left')
Plot output of both implementations
- Note the numbers are now ordered correctly.
python matplotlib not plotting y axis in order
You're passing strings here, so yes, it assumes you gave them in the order you wanted them. It doesn't know how to plot the value of a string. Convert these to floats, and you will get the results you expect.
Y-axis not properly sorted matplotlib
As DavidG suggested, I was checking my data and converted the y values from strings to integers and this solved the issue.
Try to make a Y-axis in order Python
The mal_salary
and female_salary
arrays are considered as text/string if you encase it in quotes. Remove the quotes and try...
import numpy as np
import matplotlib.pyplot as plt
# data to plot
numbers = 5
male_salary = [70942842, 178332, 9570972, 409174, 1494387]
female_salary = [32873995, 1494387, 7380776, 198272, 697929]
# create plot
fig, ax = plt.subplots(figsize=(10,5))
index = np.arange(numbers)
width = 0.40
opacity = 0.75
rects1 = plt.bar(index, male_salary, width, alpha=opacity, color='b',label='Male')
rects2 = plt.bar(index + width, female_salary, width, alpha=opacity, color='g', label='Female')
plt.xlabel("Race")
plt.ylabel("The total salary")
plt.title("Sex Differences in Salary were presented in the Private work class")
plt.xticks(index + width, ("W", "AIE", "B", "O", "API"))
plt.legend()
plt.show()
Y Axis Values Out of Order on Plotly Graph Python
I received an answer to my question on plotly and decided to share. I used a combination of both of the following techniques:
The error is due to the data types of your columns in your dataframe.
dtypes The values are of type object.However this was not a problem is previous versions of plotly (which
must be installed on your Google Collab). The newer releases requires
the values to be numeric.
You can either convert the columns to numeric like this:
#converting to type numeric
cols = weekly_data.columns.drop('DATE')
weekly_data[cols] = weekly_data[cols].apply(pd.to_numeric)
or just add autotypenumbers=‘convert types’ to update your figure:
fig = go.Figure()
fig.add_trace(go.Scatter(
x=weekly_data['DATE'],
y=weekly_data['CLOSE']))
fig.update_layout(autotypenumbers='convert types')
fig.show()
Related Topics
Difference Between Two Dates in Python
How to Get a Random Number Between a Float Range
Function for Factorial in Python
Traverse a List in Reverse Order in Python
How to Remove All Characters After a Specific Character in Python
Python Round Up Integer to Next Hundred
Multiple Axis in Matplotlib with Different Scales
Read File Data Without Saving It in Flask
Zip Variable Empty After First Use
How to Use Pip with Python 3.X Alongside Python 2.X
Replacing Few Values in a Pandas Dataframe Column with Another Value
How to Trim Whitespace from a String
How to Validate a Url in Python? (Malformed or Not)