Matplotlib Bar Chart choose color if value is positive vs value is negative












10















I have a Pandas DataFrame with positive and negative values as a bar chart. I want to plot the positive colors 'green' and the negative values 'red' (very original...lol). I'm not sure how to pass if > 0 'green' else < 0 'red'?



data = pd.DataFrame([[-15], [10], [8], [-4.5]],index=['a', 'b', 'c', 'd'],columns=['values'])
data.sort().plot(kind='barh')


enter image description here










share|improve this question





























    10















    I have a Pandas DataFrame with positive and negative values as a bar chart. I want to plot the positive colors 'green' and the negative values 'red' (very original...lol). I'm not sure how to pass if > 0 'green' else < 0 'red'?



    data = pd.DataFrame([[-15], [10], [8], [-4.5]],index=['a', 'b', 'c', 'd'],columns=['values'])
    data.sort().plot(kind='barh')


    enter image description here










    share|improve this question



























      10












      10








      10


      3






      I have a Pandas DataFrame with positive and negative values as a bar chart. I want to plot the positive colors 'green' and the negative values 'red' (very original...lol). I'm not sure how to pass if > 0 'green' else < 0 'red'?



      data = pd.DataFrame([[-15], [10], [8], [-4.5]],index=['a', 'b', 'c', 'd'],columns=['values'])
      data.sort().plot(kind='barh')


      enter image description here










      share|improve this question
















      I have a Pandas DataFrame with positive and negative values as a bar chart. I want to plot the positive colors 'green' and the negative values 'red' (very original...lol). I'm not sure how to pass if > 0 'green' else < 0 'red'?



      data = pd.DataFrame([[-15], [10], [8], [-4.5]],index=['a', 'b', 'c', 'd'],columns=['values'])
      data.sort().plot(kind='barh')


      enter image description here







      python matplotlib pandas






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 1 '17 at 19:31









      darthbith

      6,95552849




      6,95552849










      asked Mar 10 '14 at 20:58









      user3055920user3055920

      161217




      161217
























          1 Answer
          1






          active

          oldest

          votes


















          14














          I would create a dummy column for whether the observation is larger than 0.



          In [39]: data['positive'] = data['values'] > 0

          In [40]: data
          Out[40]:
          values positive
          a -15.0 False
          b 10.0 True
          c 8.0 True
          d -4.5 False

          [4 rows x 2 columns]

          In [41]: data['values'].plot(kind='barh', color=data.positive.map({True: 'r', False: 'k'}))
          Out[41]: <matplotlib.axes._subplots.AxesSubplot at 0x114b018d0>




          Also, you may want to be careful not to have column names that overlap with DataFrame attributes. DataFrame.values give the underlying numpy array for a DataFrame. Having overlapping names prevents you from using the df.<column name> syntax.






          share|improve this answer
























          • Thanks! Very nice and clean:)

            – user3055920
            Mar 10 '14 at 22:18






          • 1





            I am trying to reproduce this example with Pandas 0.20.3 amb matplotlib 2.0.2 and it doesn't work. All bars are black. Do you know why?

            – Ramon Crehuet
            Nov 2 '17 at 8:18








          • 2





            @RamonCrehuet It's a bug, see github.com/pandas-dev/pandas/issues/16822. Workaround is to put the colors in an extra list, see github.com/pandas-dev/pandas/issues/…

            – rinspy
            Feb 28 '18 at 17:06











          • Try passing color map as a list instead of pandas.Series with , data['values'].plot(kind='barh', color=[data.positive.map({True: 'r', False: 'b'})])

            – Pramit
            Apr 20 '18 at 3:18













          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%2f22311139%2fmatplotlib-bar-chart-choose-color-if-value-is-positive-vs-value-is-negative%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          14














          I would create a dummy column for whether the observation is larger than 0.



          In [39]: data['positive'] = data['values'] > 0

          In [40]: data
          Out[40]:
          values positive
          a -15.0 False
          b 10.0 True
          c 8.0 True
          d -4.5 False

          [4 rows x 2 columns]

          In [41]: data['values'].plot(kind='barh', color=data.positive.map({True: 'r', False: 'k'}))
          Out[41]: <matplotlib.axes._subplots.AxesSubplot at 0x114b018d0>




          Also, you may want to be careful not to have column names that overlap with DataFrame attributes. DataFrame.values give the underlying numpy array for a DataFrame. Having overlapping names prevents you from using the df.<column name> syntax.






          share|improve this answer
























          • Thanks! Very nice and clean:)

            – user3055920
            Mar 10 '14 at 22:18






          • 1





            I am trying to reproduce this example with Pandas 0.20.3 amb matplotlib 2.0.2 and it doesn't work. All bars are black. Do you know why?

            – Ramon Crehuet
            Nov 2 '17 at 8:18








          • 2





            @RamonCrehuet It's a bug, see github.com/pandas-dev/pandas/issues/16822. Workaround is to put the colors in an extra list, see github.com/pandas-dev/pandas/issues/…

            – rinspy
            Feb 28 '18 at 17:06











          • Try passing color map as a list instead of pandas.Series with , data['values'].plot(kind='barh', color=[data.positive.map({True: 'r', False: 'b'})])

            – Pramit
            Apr 20 '18 at 3:18


















          14














          I would create a dummy column for whether the observation is larger than 0.



          In [39]: data['positive'] = data['values'] > 0

          In [40]: data
          Out[40]:
          values positive
          a -15.0 False
          b 10.0 True
          c 8.0 True
          d -4.5 False

          [4 rows x 2 columns]

          In [41]: data['values'].plot(kind='barh', color=data.positive.map({True: 'r', False: 'k'}))
          Out[41]: <matplotlib.axes._subplots.AxesSubplot at 0x114b018d0>




          Also, you may want to be careful not to have column names that overlap with DataFrame attributes. DataFrame.values give the underlying numpy array for a DataFrame. Having overlapping names prevents you from using the df.<column name> syntax.






          share|improve this answer
























          • Thanks! Very nice and clean:)

            – user3055920
            Mar 10 '14 at 22:18






          • 1





            I am trying to reproduce this example with Pandas 0.20.3 amb matplotlib 2.0.2 and it doesn't work. All bars are black. Do you know why?

            – Ramon Crehuet
            Nov 2 '17 at 8:18








          • 2





            @RamonCrehuet It's a bug, see github.com/pandas-dev/pandas/issues/16822. Workaround is to put the colors in an extra list, see github.com/pandas-dev/pandas/issues/…

            – rinspy
            Feb 28 '18 at 17:06











          • Try passing color map as a list instead of pandas.Series with , data['values'].plot(kind='barh', color=[data.positive.map({True: 'r', False: 'b'})])

            – Pramit
            Apr 20 '18 at 3:18
















          14












          14








          14







          I would create a dummy column for whether the observation is larger than 0.



          In [39]: data['positive'] = data['values'] > 0

          In [40]: data
          Out[40]:
          values positive
          a -15.0 False
          b 10.0 True
          c 8.0 True
          d -4.5 False

          [4 rows x 2 columns]

          In [41]: data['values'].plot(kind='barh', color=data.positive.map({True: 'r', False: 'k'}))
          Out[41]: <matplotlib.axes._subplots.AxesSubplot at 0x114b018d0>




          Also, you may want to be careful not to have column names that overlap with DataFrame attributes. DataFrame.values give the underlying numpy array for a DataFrame. Having overlapping names prevents you from using the df.<column name> syntax.






          share|improve this answer













          I would create a dummy column for whether the observation is larger than 0.



          In [39]: data['positive'] = data['values'] > 0

          In [40]: data
          Out[40]:
          values positive
          a -15.0 False
          b 10.0 True
          c 8.0 True
          d -4.5 False

          [4 rows x 2 columns]

          In [41]: data['values'].plot(kind='barh', color=data.positive.map({True: 'r', False: 'k'}))
          Out[41]: <matplotlib.axes._subplots.AxesSubplot at 0x114b018d0>




          Also, you may want to be careful not to have column names that overlap with DataFrame attributes. DataFrame.values give the underlying numpy array for a DataFrame. Having overlapping names prevents you from using the df.<column name> syntax.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 10 '14 at 21:11









          TomAugspurgerTomAugspurger

          15.8k35355




          15.8k35355













          • Thanks! Very nice and clean:)

            – user3055920
            Mar 10 '14 at 22:18






          • 1





            I am trying to reproduce this example with Pandas 0.20.3 amb matplotlib 2.0.2 and it doesn't work. All bars are black. Do you know why?

            – Ramon Crehuet
            Nov 2 '17 at 8:18








          • 2





            @RamonCrehuet It's a bug, see github.com/pandas-dev/pandas/issues/16822. Workaround is to put the colors in an extra list, see github.com/pandas-dev/pandas/issues/…

            – rinspy
            Feb 28 '18 at 17:06











          • Try passing color map as a list instead of pandas.Series with , data['values'].plot(kind='barh', color=[data.positive.map({True: 'r', False: 'b'})])

            – Pramit
            Apr 20 '18 at 3:18





















          • Thanks! Very nice and clean:)

            – user3055920
            Mar 10 '14 at 22:18






          • 1





            I am trying to reproduce this example with Pandas 0.20.3 amb matplotlib 2.0.2 and it doesn't work. All bars are black. Do you know why?

            – Ramon Crehuet
            Nov 2 '17 at 8:18








          • 2





            @RamonCrehuet It's a bug, see github.com/pandas-dev/pandas/issues/16822. Workaround is to put the colors in an extra list, see github.com/pandas-dev/pandas/issues/…

            – rinspy
            Feb 28 '18 at 17:06











          • Try passing color map as a list instead of pandas.Series with , data['values'].plot(kind='barh', color=[data.positive.map({True: 'r', False: 'b'})])

            – Pramit
            Apr 20 '18 at 3:18



















          Thanks! Very nice and clean:)

          – user3055920
          Mar 10 '14 at 22:18





          Thanks! Very nice and clean:)

          – user3055920
          Mar 10 '14 at 22:18




          1




          1





          I am trying to reproduce this example with Pandas 0.20.3 amb matplotlib 2.0.2 and it doesn't work. All bars are black. Do you know why?

          – Ramon Crehuet
          Nov 2 '17 at 8:18







          I am trying to reproduce this example with Pandas 0.20.3 amb matplotlib 2.0.2 and it doesn't work. All bars are black. Do you know why?

          – Ramon Crehuet
          Nov 2 '17 at 8:18






          2




          2





          @RamonCrehuet It's a bug, see github.com/pandas-dev/pandas/issues/16822. Workaround is to put the colors in an extra list, see github.com/pandas-dev/pandas/issues/…

          – rinspy
          Feb 28 '18 at 17:06





          @RamonCrehuet It's a bug, see github.com/pandas-dev/pandas/issues/16822. Workaround is to put the colors in an extra list, see github.com/pandas-dev/pandas/issues/…

          – rinspy
          Feb 28 '18 at 17:06













          Try passing color map as a list instead of pandas.Series with , data['values'].plot(kind='barh', color=[data.positive.map({True: 'r', False: 'b'})])

          – Pramit
          Apr 20 '18 at 3:18







          Try passing color map as a list instead of pandas.Series with , data['values'].plot(kind='barh', color=[data.positive.map({True: 'r', False: 'b'})])

          – Pramit
          Apr 20 '18 at 3:18






















          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%2f22311139%2fmatplotlib-bar-chart-choose-color-if-value-is-positive-vs-value-is-negative%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

          MongoDB - Not Authorized To Execute Command

          How to fix TextFormField cause rebuild widget in Flutter

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith