Bar plot with fix color for same category in pythonmaking matplotlib scatter plots from dataframes in Python's pandasWhy isn't my Pandas 'apply' function referencing multiple columns working?Plot a scatter plot in python with matplotlib with dictionaryPlotting sorted heatmap keeping (x,y) value colorsPython: Legend has wrong colors on Pandas MultiIndex plotMost pythonic way to plot multiple signalsPlot dataframe then add vertical lines; how get custom legend text for all?Assign same color to group of line plotscreating python plot with different color linesBar plot in Pandas from several dataframes

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

Writing rule stating superpower from different root cause is bad writing

Smoothness of finite-dimensional functional calculus

can i play a electric guitar through a bass amp?

Fully-Firstable Anagram Sets

"to be prejudice towards/against someone" vs "to be prejudiced against/towards someone"

How to format long polynomial?

Is this a crack on the carbon frame?

Modeling an IPv4 Address

Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)

A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?

Test whether all array elements are factors of a number

Can a Warlock become Neutral Good?

What would happen to a modern skyscraper if it rains micro blackholes?

Have astronauts in space suits ever taken selfies? If so, how?

Minkowski space

Why do falling prices hurt debtors?

Service Entrance Breakers Rain Shield

What do you call a Matrix-like slowdown and camera movement effect?

How old can references or sources in a thesis be?

Fencing style for blades that can attack from a distance

What's the point of deactivating Num Lock on login screens?

How can I make my BBEG immortal short of making them a Lich or Vampire?

Theorems that impeded progress



Bar plot with fix color for same category in python


making matplotlib scatter plots from dataframes in Python's pandasWhy isn't my Pandas 'apply' function referencing multiple columns working?Plot a scatter plot in python with matplotlib with dictionaryPlotting sorted heatmap keeping (x,y) value colorsPython: Legend has wrong colors on Pandas MultiIndex plotMost pythonic way to plot multiple signalsPlot dataframe then add vertical lines; how get custom legend text for all?Assign same color to group of line plotscreating python plot with different color linesBar plot in Pandas from several dataframes






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








3















I have a simple dataframe as follows:



 Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 B XMA 0.482742
8 D VCD 0.469553


Now I would like to have a barplot with each value, and same color for each state if Condition is the same. I tried the following python code:



Data_Control = pd.ExcelFile('Bar_plot_example.xlsx') 
df_Control= Data_Control.parse('Sheet2')# my dataframe
s = pd.Series(df_Control.iloc[:,2].values, index=df_Control.iloc[:,1])
colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
s.plot(kind='barh', color=[colors[i] for i in df_Control['Condition']])
plt.legend()


But I am not able to get legend correctly for each condition. I am getting the following plot.
Figure



So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.










share|improve this question






























    3















    I have a simple dataframe as follows:



     Condition State Value
    0 A AM 0.775651
    1 B XP 0.700265
    2 A HML 0.688315
    3 A RMSML 0.666956
    4 B XAD 0.636014
    5 C VAP 0.542897
    6 C RMSML 0.486664
    7 B XMA 0.482742
    8 D VCD 0.469553


    Now I would like to have a barplot with each value, and same color for each state if Condition is the same. I tried the following python code:



    Data_Control = pd.ExcelFile('Bar_plot_example.xlsx') 
    df_Control= Data_Control.parse('Sheet2')# my dataframe
    s = pd.Series(df_Control.iloc[:,2].values, index=df_Control.iloc[:,1])
    colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
    s.plot(kind='barh', color=[colors[i] for i in df_Control['Condition']])
    plt.legend()


    But I am not able to get legend correctly for each condition. I am getting the following plot.
    Figure



    So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.










    share|improve this question


























      3












      3








      3








      I have a simple dataframe as follows:



       Condition State Value
      0 A AM 0.775651
      1 B XP 0.700265
      2 A HML 0.688315
      3 A RMSML 0.666956
      4 B XAD 0.636014
      5 C VAP 0.542897
      6 C RMSML 0.486664
      7 B XMA 0.482742
      8 D VCD 0.469553


      Now I would like to have a barplot with each value, and same color for each state if Condition is the same. I tried the following python code:



      Data_Control = pd.ExcelFile('Bar_plot_example.xlsx') 
      df_Control= Data_Control.parse('Sheet2')# my dataframe
      s = pd.Series(df_Control.iloc[:,2].values, index=df_Control.iloc[:,1])
      colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
      s.plot(kind='barh', color=[colors[i] for i in df_Control['Condition']])
      plt.legend()


      But I am not able to get legend correctly for each condition. I am getting the following plot.
      Figure



      So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.










      share|improve this question
















      I have a simple dataframe as follows:



       Condition State Value
      0 A AM 0.775651
      1 B XP 0.700265
      2 A HML 0.688315
      3 A RMSML 0.666956
      4 B XAD 0.636014
      5 C VAP 0.542897
      6 C RMSML 0.486664
      7 B XMA 0.482742
      8 D VCD 0.469553


      Now I would like to have a barplot with each value, and same color for each state if Condition is the same. I tried the following python code:



      Data_Control = pd.ExcelFile('Bar_plot_example.xlsx') 
      df_Control= Data_Control.parse('Sheet2')# my dataframe
      s = pd.Series(df_Control.iloc[:,2].values, index=df_Control.iloc[:,1])
      colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
      s.plot(kind='barh', color=[colors[i] for i in df_Control['Condition']])
      plt.legend()


      But I am not able to get legend correctly for each condition. I am getting the following plot.
      Figure



      So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.







      python matplotlib






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 8 at 5:07









      Shanteshwar Inde

      79811018




      79811018










      asked Mar 8 at 4:37









      Vrutang ShahVrutang Shah

      185




      185






















          2 Answers
          2






          active

          oldest

          votes


















          1














          You can create the handles and labels for the legend directly from the data:



          labels = df['Condition'].unique()
          handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
          plt.legend(handles, labels, title="Conditions")


          Complete example:



          u = """ Condition State Value
          0 A AM 0.775651
          1 B XP 0.700265
          2 A HML 0.688315
          3 A RMSML 0.666956
          4 B XAD 0.636014
          5 C VAP 0.542897
          6 C RMSML 0.486664
          7 B XMA 0.482742
          8 D VCD 0.469553"""

          import io
          import pandas as pd
          import matplotlib.pyplot as plt


          df = pd.read_csv(io.StringIO(u),sep="s+" )
          s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])
          colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
          s.plot(kind='barh', color=[colors[i] for i in df['Condition']])

          labels = df['Condition'].unique()
          handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
          plt.legend(handles, labels, title="Conditions")

          plt.show()


          enter image description here






          share|improve this answer























          • This also works! Thank you!

            – Vrutang Shah
            Mar 8 at 19:03


















          2














          So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to plt.legend.



          s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
          # Get the original handles.
          original_handles = plt.gca().get_legend_handles_labels()[0][0]

          # Hold the handles and labels that will be passed to legend in lists.
          handles = []
          labels = []
          conditions = df['Condition'].values
          # Seen conditions helps us make sure that each label is added only once.
          seen_conditions = set()
          # Iterate over the condition and handle together.
          for condition, handle in zip(conditions, original_handles):
          # If the condition was already added to the labels, then ignore it.
          if condition in seen_conditions:
          continue
          # Add the handle and label.
          handles.append(handle)
          labels.append(condition)
          seen_conditions.add(condition)

          # Call legend with the stored handles and labels.
          plt.legend(handles, labels)





          share|improve this answer























          • That works! Than you so much! Really nice code!

            – Vrutang Shah
            Mar 8 at 6:04











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056805%2fbar-plot-with-fix-color-for-same-category-in-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You can create the handles and labels for the legend directly from the data:



          labels = df['Condition'].unique()
          handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
          plt.legend(handles, labels, title="Conditions")


          Complete example:



          u = """ Condition State Value
          0 A AM 0.775651
          1 B XP 0.700265
          2 A HML 0.688315
          3 A RMSML 0.666956
          4 B XAD 0.636014
          5 C VAP 0.542897
          6 C RMSML 0.486664
          7 B XMA 0.482742
          8 D VCD 0.469553"""

          import io
          import pandas as pd
          import matplotlib.pyplot as plt


          df = pd.read_csv(io.StringIO(u),sep="s+" )
          s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])
          colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
          s.plot(kind='barh', color=[colors[i] for i in df['Condition']])

          labels = df['Condition'].unique()
          handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
          plt.legend(handles, labels, title="Conditions")

          plt.show()


          enter image description here






          share|improve this answer























          • This also works! Thank you!

            – Vrutang Shah
            Mar 8 at 19:03















          1














          You can create the handles and labels for the legend directly from the data:



          labels = df['Condition'].unique()
          handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
          plt.legend(handles, labels, title="Conditions")


          Complete example:



          u = """ Condition State Value
          0 A AM 0.775651
          1 B XP 0.700265
          2 A HML 0.688315
          3 A RMSML 0.666956
          4 B XAD 0.636014
          5 C VAP 0.542897
          6 C RMSML 0.486664
          7 B XMA 0.482742
          8 D VCD 0.469553"""

          import io
          import pandas as pd
          import matplotlib.pyplot as plt


          df = pd.read_csv(io.StringIO(u),sep="s+" )
          s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])
          colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
          s.plot(kind='barh', color=[colors[i] for i in df['Condition']])

          labels = df['Condition'].unique()
          handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
          plt.legend(handles, labels, title="Conditions")

          plt.show()


          enter image description here






          share|improve this answer























          • This also works! Thank you!

            – Vrutang Shah
            Mar 8 at 19:03













          1












          1








          1







          You can create the handles and labels for the legend directly from the data:



          labels = df['Condition'].unique()
          handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
          plt.legend(handles, labels, title="Conditions")


          Complete example:



          u = """ Condition State Value
          0 A AM 0.775651
          1 B XP 0.700265
          2 A HML 0.688315
          3 A RMSML 0.666956
          4 B XAD 0.636014
          5 C VAP 0.542897
          6 C RMSML 0.486664
          7 B XMA 0.482742
          8 D VCD 0.469553"""

          import io
          import pandas as pd
          import matplotlib.pyplot as plt


          df = pd.read_csv(io.StringIO(u),sep="s+" )
          s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])
          colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
          s.plot(kind='barh', color=[colors[i] for i in df['Condition']])

          labels = df['Condition'].unique()
          handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
          plt.legend(handles, labels, title="Conditions")

          plt.show()


          enter image description here






          share|improve this answer













          You can create the handles and labels for the legend directly from the data:



          labels = df['Condition'].unique()
          handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
          plt.legend(handles, labels, title="Conditions")


          Complete example:



          u = """ Condition State Value
          0 A AM 0.775651
          1 B XP 0.700265
          2 A HML 0.688315
          3 A RMSML 0.666956
          4 B XAD 0.636014
          5 C VAP 0.542897
          6 C RMSML 0.486664
          7 B XMA 0.482742
          8 D VCD 0.469553"""

          import io
          import pandas as pd
          import matplotlib.pyplot as plt


          df = pd.read_csv(io.StringIO(u),sep="s+" )
          s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])
          colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
          s.plot(kind='barh', color=[colors[i] for i in df['Condition']])

          labels = df['Condition'].unique()
          handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
          plt.legend(handles, labels, title="Conditions")

          plt.show()


          enter image description here







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 10:21









          ImportanceOfBeingErnestImportanceOfBeingErnest

          141k13166243




          141k13166243












          • This also works! Thank you!

            – Vrutang Shah
            Mar 8 at 19:03

















          • This also works! Thank you!

            – Vrutang Shah
            Mar 8 at 19:03
















          This also works! Thank you!

          – Vrutang Shah
          Mar 8 at 19:03





          This also works! Thank you!

          – Vrutang Shah
          Mar 8 at 19:03













          2














          So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to plt.legend.



          s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
          # Get the original handles.
          original_handles = plt.gca().get_legend_handles_labels()[0][0]

          # Hold the handles and labels that will be passed to legend in lists.
          handles = []
          labels = []
          conditions = df['Condition'].values
          # Seen conditions helps us make sure that each label is added only once.
          seen_conditions = set()
          # Iterate over the condition and handle together.
          for condition, handle in zip(conditions, original_handles):
          # If the condition was already added to the labels, then ignore it.
          if condition in seen_conditions:
          continue
          # Add the handle and label.
          handles.append(handle)
          labels.append(condition)
          seen_conditions.add(condition)

          # Call legend with the stored handles and labels.
          plt.legend(handles, labels)





          share|improve this answer























          • That works! Than you so much! Really nice code!

            – Vrutang Shah
            Mar 8 at 6:04















          2














          So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to plt.legend.



          s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
          # Get the original handles.
          original_handles = plt.gca().get_legend_handles_labels()[0][0]

          # Hold the handles and labels that will be passed to legend in lists.
          handles = []
          labels = []
          conditions = df['Condition'].values
          # Seen conditions helps us make sure that each label is added only once.
          seen_conditions = set()
          # Iterate over the condition and handle together.
          for condition, handle in zip(conditions, original_handles):
          # If the condition was already added to the labels, then ignore it.
          if condition in seen_conditions:
          continue
          # Add the handle and label.
          handles.append(handle)
          labels.append(condition)
          seen_conditions.add(condition)

          # Call legend with the stored handles and labels.
          plt.legend(handles, labels)





          share|improve this answer























          • That works! Than you so much! Really nice code!

            – Vrutang Shah
            Mar 8 at 6:04













          2












          2








          2







          So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to plt.legend.



          s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
          # Get the original handles.
          original_handles = plt.gca().get_legend_handles_labels()[0][0]

          # Hold the handles and labels that will be passed to legend in lists.
          handles = []
          labels = []
          conditions = df['Condition'].values
          # Seen conditions helps us make sure that each label is added only once.
          seen_conditions = set()
          # Iterate over the condition and handle together.
          for condition, handle in zip(conditions, original_handles):
          # If the condition was already added to the labels, then ignore it.
          if condition in seen_conditions:
          continue
          # Add the handle and label.
          handles.append(handle)
          labels.append(condition)
          seen_conditions.add(condition)

          # Call legend with the stored handles and labels.
          plt.legend(handles, labels)





          share|improve this answer













          So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to plt.legend.



          s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
          # Get the original handles.
          original_handles = plt.gca().get_legend_handles_labels()[0][0]

          # Hold the handles and labels that will be passed to legend in lists.
          handles = []
          labels = []
          conditions = df['Condition'].values
          # Seen conditions helps us make sure that each label is added only once.
          seen_conditions = set()
          # Iterate over the condition and handle together.
          for condition, handle in zip(conditions, original_handles):
          # If the condition was already added to the labels, then ignore it.
          if condition in seen_conditions:
          continue
          # Add the handle and label.
          handles.append(handle)
          labels.append(condition)
          seen_conditions.add(condition)

          # Call legend with the stored handles and labels.
          plt.legend(handles, labels)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 5:45









          Shashank AgarwalShashank Agarwal

          1,8781520




          1,8781520












          • That works! Than you so much! Really nice code!

            – Vrutang Shah
            Mar 8 at 6:04

















          • That works! Than you so much! Really nice code!

            – Vrutang Shah
            Mar 8 at 6:04
















          That works! Than you so much! Really nice code!

          – Vrutang Shah
          Mar 8 at 6:04





          That works! Than you so much! Really nice code!

          – Vrutang Shah
          Mar 8 at 6:04

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056805%2fbar-plot-with-fix-color-for-same-category-in-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved