【问题标题】:matplotlib plt not setting xlabel/ylabel correctly on scatterplotmatplotlib plt 未在散点图上正确设置 xlabel/ylabel
【发布时间】:2020-05-13 03:47:09
【问题描述】:

我正在创建一个地理图并尝试设置我的 xlabels 和 ylabels。它只显示 ylabel,但不显示 xlabel。这是一个最小的可重现示例。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

d = {
    'College': ['East Los Angeles College', 'Santa Monica Ccollege', 'American River College', 'Santa Ana College', 'Mount San Antonio College'],
    'Total Enrollment': [36606, 29999, 29701, 28698, 28481], 
    'Latitude': [34.0414, 34.0166, 38.6511, 33.7580, 34.0482],
    'Longitude': [-118.1503, -118.4704, -121.3467, -117.8889, 117.8451]
}
df = pd.DataFrame(data=d)
ax2 = df.plot.scatter(x='Longitude', y='Latitude',
                     s=df['Total Enrollment']/100, label='Enrollment',
                     c='Total Enrollment', cmap=plt.get_cmap("jet"),
                     colorbar=True, alpha=0.5, figsize=(15,12))

plt.ylabel("Latitude", fontsize=14)
plt.xlabel("Longitude", fontsize=14)

plt.legend(fontsize=16)
plt.show()

【问题讨论】:

  • 您是如何创建包含在帖子中的图像的?这是你通过plt.savefig(..)得到的图片吗?
  • 我实际上只是截取了我的 jupyter notebook 的输出
  • 也可以加plt.tight_layout()
  • @BigBen 感谢您提供该链接,对于重复的问题感到抱歉。我四处张望时一定错过了它。

标签: python pandas matplotlib scatter


【解决方案1】:

添加以下几行似乎对我有用:

fig, ax = plt.subplots()
...
df.plot.scatter(..., ax=ax)

ax.set_ylabel("Latitude", fontsize=14)
ax.set_xlabel("Longitude", fontsize=14)

尽管如 this question 中所述,调用 plt.subplots 并指定坐标轴似乎是缺失的环节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-15
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多