[英]Python pandas line plot: change x-axis to be linear
I have a pandas dataframe which looks like:我有一个熊猫数据框,它看起来像:
df.x = [2, 4, 16, 256]
df.y = [1,2,4,16]
I would like to do a line plot with linear x-axis, although the x values are not linear.我想用线性 x 轴绘制线图,尽管 x 值不是线性的。
Currently if I plot this dataframe as df.plot(), I get this because the x values are not linear:目前,如果我将此数据框绘制为 df.plot(),我会得到这个,因为 x 值不是线性的:
But, the above graph does not show the trend correctly.但是,上图并未正确显示趋势。 I want this:
我要这个:
Note that the X-axis ticks and labels are linear, though the values are not.请注意,X 轴刻度和标签是线性的,但值不是。
How can I plot the graph correctly?如何正确绘制图形? I tried renaming the xticklabels but it did not work.
我尝试重命名 xticklabels 但它没有用。
Your index ( X
axis) seems to be of object
(string) dtype) - convert it to numeric dtype before plotting.您的索引(
X
轴)似乎是object
(字符串)dtype) - 在绘图之前将其转换为数字 dtype。
Demo:演示:
In [99]: df.index.dtype
Out[99]: dtype('O') # <----- NOTE !
plotting original DF:绘制原始 DF:
In [100]: df.plot()
Out[100]: <matplotlib.axes._subplots.AxesSubplot at 0xe74e278>
let's convert index to numeric dtype and plot it again:让我们将索引转换为数字 dtype 并再次绘制它:
In [101]: df.set_index(pd.to_numeric(df.index, errors='coerce')).plot()
Out[101]: <matplotlib.axes._subplots.AxesSubplot at 0xadd94e0>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.