0

I have a bar chart question here. Given that for all the variables in the dataset 1 = yes and 0 = No. I would like to plot a bar graph with the percentages (where var=1) on the y-axis and the variables on the x axis. Thanks in advance.

Dataset

Water Ice Fire Vapor
1 1 0 1
1 0 0 1
0 1 1 1
1 1 1 1
1 1 0 1
1 1 1 0
0 1 1 1
0 1 0 1
0 1 1 1
1 0 1 1
0 1 0 0
0 1 1 0
1 0 1 0
1 0 1 0
1 1 1 1
0 1 0 1
1 0 1 1
1 0 1 0
1 1 0 1
1 0 0 1
0 1 1 1
1 1 0 1
1 0 0 1
0 1 1 1
  • A common remark here is that Stack Overflow is not a code writing service, so that you are expected to show an attempt at code and explain where you got stuck. Here you have no code at all. – Nick Cox Feb 02 '23 at 00:10
  • @Albert-Lutakome You got at least one good answer below. You ought to select the one you you like best. – dimitriy Feb 02 '23 at 22:32
  • @dimitriy I agree that there is at least one good answer, as I do like yours. – Nick Cox Feb 02 '23 at 23:18

2 Answers2

1

The percent of 1s in a (0, 1) variable is just the mean multiplied by 100. As you probably want to see the percent as text on the graph, one method is to clone the variables and multiply each by 100.

You could then use graph bar directly as it defaults to showing means. I don't like its default in this case and the code instead uses statplot, which must be installed before you can use it.

* Example generated by -dataex-. For more info, type help dataex
clear
input byte(water ice fire vapor)
1 1 0 1
1 0 0 1
0 1 1 1
1 1 1 1
1 1 0 1
1 1 1 0
0 1 1 1
0 1 0 1
0 1 1 1
1 0 1 1
0 1 0 0
0 1 1 0
1 0 1 0
1 0 1 0
1 1 1 1
0 1 0 1
1 0 1 1
1 0 1 0
1 1 0 1
1 0 0 1
0 1 1 1
1 1 0 1
1 0 0 1
0 1 1 1
end

quietly foreach v of var water-vapor {
    clonevar `v'2 = `v'
    label var `v'2 "`v'"
    replace `v'2 = 100 * `v'
}

* ssc install statplot 
statplot *2 , recast(bar) ytitle(%) blabel(bar, format(%2.1f))

Nick Cox
  • 35,529
  • 6
  • 31
  • 47
1

Try

. ssc install mylabels
checking mylabels consistency and verifying not already installed...
all files already exist and are up to date.

. sysuse nlsw88, clear
(NLSW, 1988 extract)

. mylabels 0(10)70, myscale(@/100) local(labels)
0 "0" .1 "10" .2 "20" .3 "30" .4 "40" .5 "50" .6 "60" .7 "70"

. graph bar (mean) married collgrad south union, showyvars legend(off) nolabel bargap(20) ylabel(`labels')

. table, statistic(mean married collgrad south union)

------------------------------
Married            |  .6420303
College graduate   |  .2368655
Lives in the south |  .4194123
Union worker       |  .2454739
------------------------------

This relies on mylabels, and implements the bar gap (which I also like).

enter image description here

dimitriy
  • 9,077
  • 2
  • 25
  • 50
  • Thanks for the mentions of `mylabels` now to be cited please as from the _Stata Journal_ (22(4), 2022). – Nick Cox Feb 02 '23 at 08:43