Python中散点图根据特定条件着色

发布于 2025-01-20 21:56:09 字数 1692 浏览 1 评论 0原文

我现在的目标是为欧洲地区创建子散点图。

fig, axes = plt.subplots(2,2,figsize=(10,8))
fig.tight_layout(h_pad=5.0,w_pad=3.0)

color = ['red', 'blue', 'orange']
# red = if temperature above 10
# blue = if temperature below 6
# orange = if temperature between 6 and 10 (inclusive)

# first figure for 'No EU and No Coastline'
lat1 = visualize1['latitude']
axes[0][0].scatter(city_count1List,lat1.values)
axes[0][0].set_title('No EU and No Coastline')
axes[0][0].set_xlabel('City')
axes[0][0].set_ylabel('Latitude')

# second figure for 'No EU and Yes Coastline'
lat2 = visualize2['latitude']
axes[0][1].scatter(city_count2List,lat2.values)
axes[0][1].set_title('No EU and Yes Coastline')
axes[0][1].set_xlabel('City')
axes[0][1].set_ylabel('Latitude')

# third figure for 'Yes EU and No Coastline'
lat3 = visualize3['latitude']
axes[1][0].scatter(city_count3List,lat3.values)
axes[1][0].set_title('Yes EU and No Coastline')
axes[1][0].set_xlabel('City')
axes[1][0].set_ylabel('Latitude')

# fourth figure for 'Yes EU and Yes Coastline'
lat4 = visualize4['latitude']
axes[1][1].scatter(city_count4List,lat4.values)
axes[1][1].set_title('Yes EU and Yes Coastline')
axes[1][1].set_xlabel('City')
axes[1][1].set_ylabel('Latitude')

plt.show()

我得到的结果就是我想要的格式。 输入图片这里的描述

但我想做的是根据该地区的温度使图具有不同的颜色。这是正在绘制的图表之一的示例。 输入图片此处描述

如果温度高于 10,则绘图将为红色。

如果温度在 6 到 10(含)之间,绘图将为橙色。

如果温度低于 6,则绘图将为蓝色。

有什么方法可以用上面的代码来做到这一点吗?

My goal right now is to create sub scatter plots for regions in Europe.

fig, axes = plt.subplots(2,2,figsize=(10,8))
fig.tight_layout(h_pad=5.0,w_pad=3.0)

color = ['red', 'blue', 'orange']
# red = if temperature above 10
# blue = if temperature below 6
# orange = if temperature between 6 and 10 (inclusive)

# first figure for 'No EU and No Coastline'
lat1 = visualize1['latitude']
axes[0][0].scatter(city_count1List,lat1.values)
axes[0][0].set_title('No EU and No Coastline')
axes[0][0].set_xlabel('City')
axes[0][0].set_ylabel('Latitude')

# second figure for 'No EU and Yes Coastline'
lat2 = visualize2['latitude']
axes[0][1].scatter(city_count2List,lat2.values)
axes[0][1].set_title('No EU and Yes Coastline')
axes[0][1].set_xlabel('City')
axes[0][1].set_ylabel('Latitude')

# third figure for 'Yes EU and No Coastline'
lat3 = visualize3['latitude']
axes[1][0].scatter(city_count3List,lat3.values)
axes[1][0].set_title('Yes EU and No Coastline')
axes[1][0].set_xlabel('City')
axes[1][0].set_ylabel('Latitude')

# fourth figure for 'Yes EU and Yes Coastline'
lat4 = visualize4['latitude']
axes[1][1].scatter(city_count4List,lat4.values)
axes[1][1].set_title('Yes EU and Yes Coastline')
axes[1][1].set_xlabel('City')
axes[1][1].set_ylabel('Latitude')

plt.show()

The result I get is what I want in terms of formatting.
enter image description here

But what I want to do is make the plots different colors depending on the temperature of the region. Here's an example of one of the charts that are being graphed.
enter image description here

If the temperature is above 10, then the plot will be red.

If the temperature is between 6 and 10 (inclusive), the plot will be orange.

If the temperature is below 6, then the plot will be blue.

Is there some way I can do this with the code above?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

垂暮老矣 2025-01-27 21:56:09

根据条件创建了一个分类颜色列应用颜色

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

city = ["abc","def","ghi","jkl","mno","pqr","stu","vwx", "yza", "bcd"]
eu = ["no","no","no","no","no","no","no","no","no","no"]
coast = ["no","no","no","no","no","no","no","no","no","no"]
lat = [42.50,52.61,52.10,42,47.76,44.82,44.82,6.68,6.43,8.40]
temp = [7.50,5.61,4.10,8,9.76,10.82,3.82,4.68,1.43,5.40]

df1 = pd.DataFrame({'city':city, 'eu':eu, 'coast':coast, 'latitude':lat, 'temprature':temp})


df1.loc[df1['temprature'] > 10, 'color'] = 'R'
df1.loc[((df1['temprature'] > 6) & (df1['temprature'] <= 10)), 'color'] = 'O'
df1.loc[df1['temprature'] < 6, 'color'] = 'B'

fig, ax = plt.subplots(figsize=(6, 6))
colors = {'R':'tab:red', 'O':'tab:orange', 'B':'tab:blue'}
ax.scatter(df1['temprature'], df1['latitude'], c=df1['color'].map(colors))

handles = [Line2D([0], [0], marker='o', color='w', markerfacecolor=v, label=k, markersize=8) for k, v in colors.items()]
ax.legend(title='color', handles=handles, bbox_to_anchor=(1.05, 1), loc='upper left')

plt.show()

Created a categorical color column based on the condition & applied color

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

city = ["abc","def","ghi","jkl","mno","pqr","stu","vwx", "yza", "bcd"]
eu = ["no","no","no","no","no","no","no","no","no","no"]
coast = ["no","no","no","no","no","no","no","no","no","no"]
lat = [42.50,52.61,52.10,42,47.76,44.82,44.82,6.68,6.43,8.40]
temp = [7.50,5.61,4.10,8,9.76,10.82,3.82,4.68,1.43,5.40]

df1 = pd.DataFrame({'city':city, 'eu':eu, 'coast':coast, 'latitude':lat, 'temprature':temp})


df1.loc[df1['temprature'] > 10, 'color'] = 'R'
df1.loc[((df1['temprature'] > 6) & (df1['temprature'] <= 10)), 'color'] = 'O'
df1.loc[df1['temprature'] < 6, 'color'] = 'B'

fig, ax = plt.subplots(figsize=(6, 6))
colors = {'R':'tab:red', 'O':'tab:orange', 'B':'tab:blue'}
ax.scatter(df1['temprature'], df1['latitude'], c=df1['color'].map(colors))

handles = [Line2D([0], [0], marker='o', color='w', markerfacecolor=v, label=k, markersize=8) for k, v in colors.items()]
ax.legend(title='color', handles=handles, bbox_to_anchor=(1.05, 1), loc='upper left')

plt.show()
沙沙粒小 2025-01-27 21:56:09

我没有时间手动复制您在图片中发布的数据,因此我将生成随机数据。

有许多应用条件颜色的方法。这是我的方法:

import numpy as np
import matplotlib.pyplot as plt

# generate random data
x = np.random.uniform(0, 1, 10)
y = np.random.uniform(0, 1, 10)
temp = np.array([1, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# the idea is to build a list of colors.
# Please, read help(plt.scatter) to understand
# how colors should be presented. Also, read this
# documentation page:
# https://matplotlib.org/3.5.0/tutorials/colors/colors.html

# insert your conditions here (I'm going to use Tab10 colors)
def case(t):
    if t > 10:
        return "tab:red"
    elif (t > 6) and (t <= 10):
        return "tab:orange"
    return "tab:blue"
colors = [col_dict[case(t)] for t in temp]

plt.figure()
plt.scatter(x, y, c=colors)
plt.xlabel("City")
plt.ylabel("Latitude")

“在此处输入图像描述”

I don't have time to manually copy the data you posted in the pictures, so I'm going to generate random data.

There are many ways to apply conditional colors. This is my approach:

import numpy as np
import matplotlib.pyplot as plt

# generate random data
x = np.random.uniform(0, 1, 10)
y = np.random.uniform(0, 1, 10)
temp = np.array([1, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# the idea is to build a list of colors.
# Please, read help(plt.scatter) to understand
# how colors should be presented. Also, read this
# documentation page:
# https://matplotlib.org/3.5.0/tutorials/colors/colors.html

# insert your conditions here (I'm going to use Tab10 colors)
def case(t):
    if t > 10:
        return "tab:red"
    elif (t > 6) and (t <= 10):
        return "tab:orange"
    return "tab:blue"
colors = [col_dict[case(t)] for t in temp]

plt.figure()
plt.scatter(x, y, c=colors)
plt.xlabel("City")
plt.ylabel("Latitude")

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文