GVKun编程网logo

有没有办法在python中按大小对水平条形图进行排序?(有没有办法在python中按大小对水平条形图进行排序操作)

4

针对有没有办法在python中按大小对水平条形图进行排序?和有没有办法在python中按大小对水平条形图进行排序操作这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展c#–有没有办法在不分配任

针对有没有办法在python中按大小对水平条形图进行排序?有没有办法在python中按大小对水平条形图进行排序操作这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展c# – 有没有办法在不分配任何内存的情况下对数组进行排序?、使用Matplotlib在Python中绘制数据框-水平条形图、使用Python的高级水平条形图?、使用快速排序按频率对元素进行排序:如何按大小对相同频率的元素进行排序?等相关知识,希望可以帮助到你。

本文目录一览:

有没有办法在python中按大小对水平条形图进行排序?(有没有办法在python中按大小对水平条形图进行排序操作)

有没有办法在python中按大小对水平条形图进行排序?(有没有办法在python中按大小对水平条形图进行排序操作)

如何解决有没有办法在python中按大小对水平条形图进行排序??

我下面的代码使用标题列表和百分比列表制作水平条形图。标题在 y 轴上,百分比在 x 轴上。下面有一张图片,假设职位在 y 轴上。我想根据最大的条对条进行排序,相应的标题在顶部,较小的在底部。我该怎么做?

enter image description here

plt.rcdefaults()
fig,ax = plt.subplots()
y_pos = np.arange(len(y))
ax.barh(y_pos,percents_usage,color=''lawngreen'')
ax.set_yticks(y_pos)
ax.set_yticklabels(y)
ax.set_xlim(0,100)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel(''Permission Usage %'')
ax.set_title(''Permissions Usage % by Title'')

plt.show()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

c# – 有没有办法在不分配任何内存的情况下对数组进行排序?

c# – 有没有办法在不分配任何内存的情况下对数组进行排序?

我需要非常频繁地对一个相当大的集合(高数百/低数千项)进行排序,即每帧60 fps(我使用Unity).
计算每个项目的密钥有点慢,因此需要进行缓存.

我尝试了各种方法:

> List.sort()与IComparer,每次计算密钥:超级慢
> SortedList:更快,但生成GC分配(30KB /帧):为什么?是他们的钥匙盒装(我用了很长时间)?是分配的键/值对?如果我将long包装在一个类中,那么GC减半,所以我的猜测是“both”:1为该对分配,如果它是值类型,则分配一个用于键入密钥…
> Array.sort(keyArray,valueArray):可怕的!慢慢的生成256KB的GC /帧!

这是一个耻辱,因为SortedList似乎是完美的工作,有没有我没有的GC替代品?

解决方法

如果计算键太慢,您可以将key属性添加到item类,在排序之前计算它,然后使用IComparer的第一个方法简单地比较键.

使用Matplotlib在Python中绘制数据框-水平条形图

使用Matplotlib在Python中绘制数据框-水平条形图

您可以使用此代码水平绘制图形

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


plt.rcdefaults()
fig,ax = plt.subplots()

# Example data
people = ('Tom','Dick','Harry','Slim','Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos,performance,xerr=error,align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()
Copy to clipboard
,

欢迎我的朋友来stackoverflow。作为建议,最好显示一下数据框。我这样创建了一个虚拟数据框;

enter image description here

首先,您需要将Year变量设为分类(只是一个建议)

df["Year"] = df["Year"].astype('category')

然后我用了这段代码

ax = df.plot(x="Year",y="Var1",kind="bar")
df.plot(x="Year",y="Var2",kind="bar",ax=ax,color="C2")

输出是这样的

enter image description here

使用Python的高级水平条形图?

使用Python的高级水平条形图?

tutorial for vertical gradient bars可以用来绘制水平条,中间的黑点最深:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.colors as mcolors
import numpy as np

def hor_gradient_image(ax,extent,darkest,**kwargs):
    '''
    puts a horizontal gradient in the rectangle defined by extent (x0,x1,y0,y1)
    darkest is a number between 0 (left) and 1 (right) setting the spot where the gradient will be darkest
    '''
    ax = ax or plt.gca()
    img = np.interp(np.linspace(0,1,100),[0,1],0]).reshape(1,-1)
    return ax.imshow(img,extent=extent,interpolation='bilinear',vmin=0,vmax=1,**kwargs)

def gradient_hbar(y,x0,ax=None,height=0.8,darkest=0.5,cmap=plt.cm.PuBu):
    hor_gradient_image(ax,extent=(x0,y - height / 2,y + height / 2),cmap=cmap,darkest=darkest)
    rect = mpatches.Rectangle((x0,y - height / 2),x1 - x0,height,edgecolor='black',facecolor='none')
    ax.add_patch(rect)

# cmap = mcolors.LinearSegmentedColormap.from_list('turq',['paleturquoise','darkturquoise'])
cmap = mcolors.LinearSegmentedColormap.from_list('turq',['#ACFAFA','#3C9E9E'])
fig,ax = plt.subplots()
for y in range(1,11):
    x0,x1 = np.sort(np.random.uniform(1,9,2))
    gradient_hbar(y,ax=ax,height=0.7,cmap=cmap)
ax.set_aspect('auto')
ax.use_sticky_edges = False
ax.autoscale(enable=True,tight=False)
ax.grid(axis='x')
plt.show()

example plot

使用快速排序按频率对元素进行排序:如何按大小对相同频率的元素进行排序?

使用快速排序按频率对元素进行排序:如何按大小对相同频率的元素进行排序?

如何解决使用快速排序按频率对元素进行排序:如何按大小对相同频率的元素进行排序??

我正在尝试使用快速排序在 Python 中解决这个问题:

给定一个整数数组 A[],根据元素的频率对数组进行排序。即具有较高频率的元素首先出现。如果两个元素的频率相同,则较小的数字在前。

我已经创建了一个数组来存储每个整数在 A[] 中出现的次数,如下所示:

def find_count(arr,n):
    count = [0]*(max(arr)+1)
    for i in arr:
        count[i] += 1
    return count

接下来,我使用快速排序按出现次数的降序对元素进行排序:

def quicksort(arr,low,high,count):
    if(low < high):
        i = low
        j = high
        pivot = low
        while(i < j):
            while(i < high and count[arr[i]] >= count[arr[pivot]]):
                i += 1
            while(count[arr[j]] < count[arr[pivot]]):
                j -= 1
            if(i < j):
                arr[i],arr[j] = arr[j],arr[i]
        arr[pivot],arr[pivot]
        quicksort(arr,j-1,count)
        quicksort(arr,j+1,count)

此方法用于按频率降序对元素进行排序。但是,具有相同频率的元素以不可预测的顺序出现(不是按要求按大小递增的顺序):

For Input:
[5,5,4,6,4]
your output is: 
[5,6]
required output:
[4,6]

如何实现一个条件以按大小递增的顺序对具有相同频率的元素进行排序?

解决方法

您修改了快速排序,使其使用一个键函数

  • 类似于 Python 排序函数如何使用键函数
  • 更通用的解决方案,因为可以使用不同的键函数按其他标准进行排序

修改后的代码

def find_count(arr,n):
    count = [0]*(max(arr)+1)
    for i in arr:
        count[i] += 1
    return count

def quicksort(arr,low,high,keyfunc):
    if(low < high):
        i = low
        j = high
        pivot = low
        while i < j:
            while i < high and keyfunc(arr[i]) >= keyfunc(arr[pivot]):
                i += 1
            while keyfunc(arr[j]) < keyfunc(arr[pivot]):
                j -= 1
            if i < j:
                arr[i],arr[j] = arr[j],arr[i]
        arr[pivot],arr[pivot]
        quicksort(arr,j-1,keyfunc)
        quicksort(arr,j+1,keyfunc)

测试

a = [5,5,4,6,4]
count = find_count(a,len(a))

# Use key function based upon tuple of count and value (use -v since want lower values first)
quicksort(a,len(a)-1,lambda v: (count[v],-v)) 
# new a: [5,4]

# Change key function to sort strings
a = [''to'',''be'',''or'',''not'',''to'',''a'',''fool'']
quicksort(a,lambda v: (-len(v),v))
# new a: [''a'',''fool'']
,

我通过修改 quicksort() 函数以仅交换大小顺序错误的相同频率的元素来解决该问题:

def quicksort(arr,count):
if(low < high):
    i = low
    j = high
    pivot = low
    while(i < j):
        while(i < high and (count[arr[i]] > count[arr[pivot]] or
           (count[arr[i]] == count[arr[pivot]] and arr[i] <= arr[pivot]))):
            i += 1
        while( j >= low and count[arr[j]] < count[arr[pivot]] or
           (count[arr[j]] == count[arr[pivot]] and arr[j] > arr[pivot])):
            j -= 1
        if(i < j):
            arr[i],arr[i]
    arr[pivot],arr[pivot]
    quicksort(arr,count)
    quicksort(arr,count)

通过这种方式,我能够根据所需的条件对数组进行排序。

,
package javaapplication4;

import java.util.HashMap;
import java.util.Map;

public class QuickSort {

    int arr[];
    int freq[];
    HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();

    QuickSort(int arr[]) {
        this.arr = arr;
        freq = new int[arr.length];
    }
 
    void qsortByFrequency(int low,int high) {
        if (low < high) {

            int pi = partitionByFrequency(low,high);
            qsortByFrequency(low,pi - 1);
            qsortByFrequency(pi + 1,high);
        }
    }

    int partitionByFrequency(int low,int high) {
        int pivot = freq[high];
        int i = low - 1;
        int j;
        for (j = low; j <= high; j++) {
            if (freq[j] < pivot) {
                i++;
                int temp = freq[i];
                freq[i] = freq[j];
                freq[j] = temp;

                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        int temp = freq[i + 1];
        freq[i + 1] = freq[high];
        freq[high] = temp;

        temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;
        return i + 1;
    }

    void getFrequency() {

        for (int i = 0; i < arr.length; i++) {
            if (map.containsKey(arr[i])) {
                int c = map.get(arr[i]);
                map.put(arr[i],++c);

            } else {
                map.put(arr[i],1);

            }
        }

        for (int i = 0; i < this.arr.length; i++) {
            int el = arr[i];
            int c = map.get(arr[i]);
            freq[i] = c;
        }

        System.out.println("FreqMap " + map);
        this.qsortByFrequency(0,this.freq.length - 1);

    }

    void getSortedArray() {

        System.out.println(" Quick Sorted Array ");
        for (int i = 0; i < this.arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println(" -- ");
    }
}

今天关于有没有办法在python中按大小对水平条形图进行排序?有没有办法在python中按大小对水平条形图进行排序操作的介绍到此结束,谢谢您的阅读,有关c# – 有没有办法在不分配任何内存的情况下对数组进行排序?、使用Matplotlib在Python中绘制数据框-水平条形图、使用Python的高级水平条形图?、使用快速排序按频率对元素进行排序:如何按大小对相同频率的元素进行排序?等更多相关知识的信息可以在本站进行查询。

本文标签: