I have a Django model that contains all the songs all users have added to the playlist of a service. I want to display the 20 most requested songs with a stacked bar chart, with colors showing the different users who have added the song.
我有一个Django模型,它包含所有用户添加到服务播放列表中的所有歌曲。我想用堆叠的条形图显示点击量最大的20首歌曲,用颜色显示添加了歌曲的不同用户。
My problem is that I have been unable to sort the Plotly graph by the total height of the Y-axis. Instead it sorts the columns by the highest individual value (the amount of times the user with most requests of given song has requested it.).
我的问题是,我无法按Y轴的总高度对Ploly图形进行排序。相反,它按照最高的单个值对列进行排序(对给定歌曲有最多请求的用户请求的次数)。
The current result of stacked bars
堆叠条形图的当前结果
This is what my django models look like:
这是我的Django模型的样子:
class Song(models.Model):
adders = models.ManyToManyField(Syncer)
name = models.CharField(max_length=255, null=True)
video_id = models.CharField(max_length=255)
def __str__(self):
return(f"Song: {self.name}, adders: {self.adders}")
class QueueEntry(models.Model):
entry_id = models.IntegerField(primary_key=True)
user = models.ForeignKey(Syncer, on_delete=models.CASCADE)
song = models.ForeignKey(Song, on_delete= models.CASCADE)
added_time = models.DateTimeField()
I get the names of the 20 most played songs in the django view with this
我得到了Django视图中播放次数最多的20首歌曲的名称
most_played = Song.objects.annotate(times_added=Count('queueentry', distinct=True)).order_by("-times_added")[1:20]
播放次数最多=Song.objects.annotate(times_added=Count(‘queueentry’,distinct=True)).order_by(“-times_added”)[1:20]
and I use that to get a QueueEntry queryset that contains all individual song requests of the 20 most played songs.
我使用它来获得一个QueueEntry查询集,其中包含20首播放次数最多的歌曲的所有单独歌曲请求。
song_ids = most_played.values_list('id', flat=True)
all= QueueEntry.objects.filter(song__id__in=song_ids)
Then I create a panda dataframe using django_pandas.io and perform grouping and aggregating
然后,我使用django_anda as.io创建一个Panda数据帧并执行分组和聚合
from django_pandas.io import read_frame
import pandas as pd
import plotly.express as px
df = read_frame(all)
song_counts = df.groupby(['song', 'user']).agg(item_count=('entry_id', 'count')).reset_index()
print(song_counts)
the print(song_counts) outputs the data in a seemingly correct order
Print(Song_Count)以看似正确的顺序输出数据
index |
song |
user |
itemcount |
1 |
oksong |
mike |
3 |
2 |
oksong |
jack |
1 |
3 |
goodsong |
sarah |
2 |
4 |
badsong |
anna |
1 |
And finally I create a stacked bar chart.
最后,我创建了一个堆叠的条形图。
fig = px.bar( song_counts, x='song', y='item_count', color='user', color_continuous_scale='blues', #color_continuous_midpoint=6, title=f'Songs')
FIG=px.bar(Song_count,x=‘Song’,y=‘Item_count’,COLOR=‘USER’,COLOR_CONTINUE_SCALE=‘蓝调’,#COLOR_CONTINUE_MIDPOINT=6,TITLE=f‘Songes’)
Where is the problem in my code? Why aren't the bars being sorted by their TOTAL height (all individual users itemcounts of the song added together)
我的代码中的问题在哪里?为什么不按它们的总高度排序(将歌曲的所有单独用户项目计数加在一起)
更多回答
我是一名优秀的程序员,十分优秀!