Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

418
Views
Cómo trazar un gráfico de barras de conteo con Pandas DF, agrupando por una columna categórica y coloreando por otra

Tengo un marco de datos que se ve más o menos así:

 Property Name industry 1 123 name1 industry 1 1 144 name1 industry 1 2 456 name2 industry 1 3 789 name3 industry 2 4 367 name4 industry 2 . ... ... ... . ... ... ... n 123 name1 industry 1

Quiero hacer un gráfico de barras que represente cuántas filas hay para cada uno de los nombres y colorear las barras según la industria. He intentado algo como esto:

 ax = df['name'].value_counts().plot(kind='bar', figsize=(14,8), title="Number for each Owner Name") ax.set_xlabel("Owner Names") ax.set_ylabel("Frequency")

me sale lo siguiente:

casi ahí

Mi pregunta es cómo coloreo las barras de acuerdo con la columna de la industria en el marco de datos (y agrego una leyenda).

¡Gracias!

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Esta es mi respuesta:

 def plot_bargraph_with_groupings(df, groupby, colourby, title, xlabel, ylabel): """ Plots a dataframe showing the frequency of datapoints grouped by one column and coloured by another. df : dataframe groupby: the column to groupby colourby: the column to color by title: the graph title xlabel: the x label, ylabel: the y label """ import matplotlib.patches as mpatches # Makes a mapping from the unique colourby column items to a random color. ind_col_map = {x:y for x, y in zip(df[colourby].unique(), [plt.cm.Paired(np.arange(len(df[colourby].unique())))][0])} # Find when the indicies of the soon to be bar graphs colors. unique_comb = df[[groupby, colourby]].drop_duplicates() name_ind_map = {x:y for x, y in zip(unique_comb[groupby], unique_comb[colourby])} c = df[groupby].value_counts().index.map(lambda x: ind_col_map[name_ind_map[x]]) # Makes the bargraph. ax = df[groupby].value_counts().plot(kind='bar', figsize=FIG_SIZE, title=title, color=[c.values]) # Makes a legend using the ind_col_map legend_list = [] for key in ind_col_map.keys(): legend_list.append(mpatches.Patch(color=ind_col_map[key], label=key)) # display the graph. plt.legend(handles=legend_list) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel)

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo Report

0

Usar seaborn.countplot

 import seaborn as sns sns.set(style="darkgrid") titanic = sns.load_dataset("titanic") ax = sns.countplot(x="class", data=titanic)

Consulte la documentación de seaborn https://seaborn.pydata.org/generated/seaborn.countplot.html

over 4 years ago · Santiago Trujillo Report

0

Puede ser un poco demasiado complicado, pero esto hace el trabajo. Primero definí las asignaciones de nombre a industria y de industria a color (parece que solo hay dos industrias, pero puede ajustar el diccionario a su caso):

 ind_col_map = { "industry1": "red", "industry2": "blue" } unique_comb = df[["Name","industry"]].drop_duplicates() name_ind_map = {x:y for x, y in zip(unique_comb["Name"],unique_comb["industry"])}

Luego, el color se puede generar utilizando las dos asignaciones anteriores:

 c = df['Name'].value_counts().index.map(lambda x: ind_col_map[name_ind_map[x]])

Finalmente, solo necesita agregar color a su función de trazado:

 ax = df['Name'].value_counts().plot(kind='bar', figsize=(14,8), title="Number for each Owner Name", color=c) ax.set_xlabel("Owner Names") ax.set_ylabel("Frequency") plt.show()

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!