I want to plot y_1 on x and y_1 on y axis for being ideal line but there is an error.
The following is my code,
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def plot_me():
df = pd.DataFrame({
'y_1': [20, 30, 290, 675, 800],
'y_2': [22, 25, 281, 600, 900]
}, index=[1990, 1997, 2003, 2009, 2014])
df.plot.line(x='y_1', y='y_2')
df.plot.line(x='y_1', y='y_1')
plt.show()
plot_me()
File "/home/MyUser/.local/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 3623, in get_loc raise KeyError(key) from err
However, this works if I change to,
df.plot.scatter(x=’y_1′, y=’y_1′)
df.plot.scatter(x=’y_1′, y=’y_1′)
and it works
>Solution :
Pandas’ plotting functionality does not support plotting the same data on both the x-axis and y-axis directly. The reason for this limitation is that pandas’ plotting methods are primarily designed for visualizing relationships between different columns or variables in a DataFrame.
If you want to plot the same data on both the x-axis and y-axis, you can use matplotlib directly to achieve this. Here’s an example of how you can modify the code to plot the same data on both axes using matplotlib:
import pandas as pd
import matplotlib.pyplot as plt
def plot_me():
df = pd.DataFrame({
'y_1': [20, 30, 290, 675, 800],
'y_2': [22, 25, 281, 600, 900]
}, index=[1990, 1997, 2003, 2009, 2014])
fig, ax = plt.subplots()
ax.plot(df['y_1'], df['y_1'], label='y_1')
ax.set_xlabel('y_1')
ax.set_ylabel('y_1')
ax.legend()
plt.show()
plot_me()