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 to explain what's wrong with this application of the chain rule?

Store Credit Card Information in Password Manager?

Is there a name for this algorithm to calculate the concentration of a mixture of two solutions containing the same solute?

C++ debug/print custom type with GDB : the case of nlohmann json library

What if a revenant (monster) gains fire resistance?

Why electric field inside a cavity of a non-conducting sphere not zero?

Should I outline or discovery write my stories?

Is it improper etiquette to ask your opponent what his/her rating is before the game?

Added a new user on Ubuntu, set password not working?

Biological Blimps: Propulsion

copy and scale one figure (wheel)

How do I color the graph in datavisualization?

How can Trident be so inexpensive? Will it orbit Triton or just do a (slow) flyby?

Why can Carol Danvers change her suit colours in the first place?

Does a 'pending' US visa application constitute a denial?

Why is so much work done on numerical verification of the Riemann Hypothesis?

Drawing ramified coverings with tikz

How to implement a feedback to keep the DC gain at zero for this conceptual passive filter?

250 Floor Tower

Has any country ever had 2 former presidents in jail simultaneously?

How to bake one texture for one mesh with multiple textures blender 2.8

Fear of getting stuck on one programming language / technology that is not used in my country

What is this cable/device?

2.8 Why are collections grayed out? How can I open them?



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













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

      6231818




      6231818










      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

          139k13161239




          139k13161239












          • 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

          Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

          Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

          How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page