重叠标签:如何在同一刻度上对名称进行分组?

问题描述 投票:0回答:1

我一直在努力处理Python中的绘图和重叠问题。我有一个类似于以下的数据集:

ID  TV            Start
1  gameofthrones   21:34:00
2  beverlyhills    21:34:00
3  modernfamiily   00:34:00
4  housemd         01:34:00
5  hunters         01:34:00
4  housed          01:34:00
7  beautiful       01:34:00
8  theoffice       01:34:00
...
9  lacasadepapel   16:34:00
10 mrroobot        16:34:00

当我绘制它时,我得到了可怕的结果:

enter image description here

使用此代码:

import matplotlib.pyplot as plt 

plt.figure(figsize=(16,8))
plt.plot(df['TV'],df['Start'])
plt.show()

我还尝试过旋转标签(plt.xticks(rotation=70)):没事,仍然很可怕!我以为可能是因为有很多电视系列名称的开始时间都相同(在x轴上按出现时间排序,即从00:00到23:59),所以可能解决方案是将电视名称同时分组在一个列表中,以便不可视化名称的重叠。但是我不知道该怎么做。

当然,如果您还有其他避免重叠的建议,我很乐意听取他们的意见。

python pandas matplotlib data-visualization
1个回答
0
投票
  • 时间是自变量,应该在x轴上。这样也可以解决x轴上的值过多的问题。
  • Start列是一个字符串,而不是日期时间,并且plot api不会连续对其进行排序,因此应对其进行排序。
import pandas as pd
import seaborn as sns
import maplotlib.pyplot as plt

# data
data = {'ID': [1, 2, 3, 4, 5, 4, 7, 8, 9, 10],
        'TV': ['gameofthrones', 'beverlyhills', 'modernfamiily', 'housemd', 'hunters', 'housed', 'beautiful', 'theoffice', 'lacasadepapel', 'mrroobot'],
        'Start': ['21:34:00', '21:34:00', '00:34:00', '01:34:00', '01:34:00', '01:34:00', '01:34:00', '01:34:00', '16:34:00', '16:34:00']}

# dataframe
df = pd.DataFrame(data)

# sort by Start
df.sort_values('Start', inplace=True)

# plot
p = sns.scatterplot('Start', 'TV', data=df)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.