Ich versuche, meine eigenen Etiketten für ein Seaborn-Barplot mit folgendem Code zu verwenden:
import pandas as pd
import seaborn as sns
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat',
data = fake,
color = 'black')
fig.set_axis_labels('Colors', 'Values')
Ich erhalte jedoch eine Fehlermeldung, dass:
AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels'
Was gibt?
Seaborns Barplot liefert ein Achsenobjekt (keine Figur). Dies bedeutet, dass Sie Folgendes tun können:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat',
data = fake,
color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()
Man kann die AttributeError
, die durch die set_axis_labels()
-Methode hervorgerufen wird, vermeiden, indem man die matplotlib.pyplot.xlabel
und matplotlib.pyplot.ylabel
.
matplotlib.pyplot.xlabel
legt die Beschriftung der x-Achse fest, während matplotlib.pyplot.ylabel
setzt die Beschriftung der y-Achse der aktuellen Achse.
Lösungscode:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)
Ausgangszahl:
Sie können den Titel Ihres Diagramms auch festlegen, indem Sie den title-Parameter wie folgt hinzufügen
ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')
Sie haben nur einen Fehler mit fig.set_axis_labels () gemacht.
folgen Sie der besten Lösung
import pandas as pd # for data anlisys
import seaborn as sns # for data visualization
import matplotlib.pyplot as plt # for data visualization
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat',
data = fake,
color = 'black')
plt.title("Barplot of Values and Colors", fontsize = 20)
plt.xlabel("Values", fontsize = 15)
plt.ylabel("Colors", fontsize = 15)
plt.show()
Klicken Sie hier, um die Ausgabe zu sehen
Sie können auch verwenden
fig.set(title = "Barplot of Values and Colors",
xlabel = "Values",
ylabel = "Colors")
Danke