xlabel and ylabel values are not sorted in matplotlib scatterplot

走远了吗. 提交于 2021-02-10 12:06:54

问题


I have done tedious amounts of searching on the internet and it seems that I have not been able to figure out how to ask the right question to get the answer for what I want to do.

I am trying to create a scatterplot with P/E ratio on the y-axis and Dividend Yield on the x-axis. I put the data into a CSV file and then imported each column into Python as individual lists.

Here is how my scatterplot turns out below. I am confused why the x- and y- axes are not sorted numerically. I think I have to turn the elements within the list into floats and then do some sort of sort before turning it into a scatterplot.

The other option I can think of is being able to sort the values in the process of creating the scatterplot.

Neither of these have worked out and I have reached a dead end. Any help or pointing in the right direction would be much appreciated as I can only describe my problem, but don't seem to be able to be asking the right questions in my search.

scatterplot from matplotlib


回答1:


You need to convert your strings to numbers. Matplotlib treats strings as “categories”, and plots them in the order you supply them...




回答2:


I don't have enough rep to reply to comments on OPs response to Jody's comment, but I wanted to add that that did solve the issue for me, but if you're having the same problem that I have where you have multiple types in your dataframe, convert just one column using format:

df["colName"] = pd.to_numeric(df["colName"])

Hope this helps someone




回答3:


import matplotlib.pyplot as plt

#arrays (X,Y) from your csv file with all of your data
x = [<some values>]
y = [<some values>]

plt.scatter(X,Y)

This will give you a plot where the coordinates of each point is

(x[i],y[i])

From what I know, it does not sort the data automatically for you before it plots. If you want sorted data, you will have to first have to do something like

x.sort()
y.sort()

and then store them in a new variable and then put that into the scatter function.

Another problem I see is that in your scatter plot, the X and Y axis labels are not in order. I have never seen this before and I am not sure why it is like this. Could you provide some code in order to diagnose why that could be happening?



来源:https://stackoverflow.com/questions/51341717/xlabel-and-ylabel-values-are-not-sorted-in-matplotlib-scatterplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!